Fork me on GitHub

【第二篇】xLua中lua加载方式

 xLua中lua文件加载方式

1. 直接执行字符串方式

1 LuaEnv luaenv = new LuaEnv();
2 luaenv.DoString("CS.UnityEngine.Debug.Log('hello world')");
3 luaenv.Dispose();

2. 通过require加载lua文件方式,require加载的文件路径包括Resources和内置的一些路径。在Resources下存放一个HelloWorld.lua.txt文件

1 LuaEnv luaenv = new LuaEnv();
2 luaenv.DoString("require 'HelloWorld'");
3 luaenv.Dispose();

3. 自定义loader加载 

 

 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using System.Net;
 5 using UnityEngine;
 6 using XLua;
 7 
 8 public class MyLuaTest : MonoBehaviour
 9 {
10     private LuaEnv _luaEnv = null;
11     // Start is called before the first frame update
12     void Start()
13     {
14         _luaEnv = new LuaEnv();
15         _luaEnv.AddLoader(CustomMyLoader);
16         _luaEnv.DoString("require 'CustomDIRLuaFile'");
17     }
18 
19     private static byte[] CustomMyLoader(ref string fileName)
20     {
21         byte[] byArrayReturn = null;
22         
23         // 定义lua路径
24         string luaPath = Application.dataPath + "/Scripts/LuaScripts/" + fileName + ".lua";
25         // 读取lua路径中指定lua文件内容
26         string strLuaContent = File.ReadAllText(luaPath);
27         // 数据类型转换
28         byArrayReturn = System.Text.Encoding.UTF8.GetBytes(strLuaContent);
29     
30         return byArrayReturn;
31     }
32     
33     void OnDestroy()
34     {
35         _luaEnv.Dispose();
36     }
37 }

注释:

  通过AddLoader可以注册回调,该回调参数是字符串,lua代码里调用require是,参数将会自动传给回调,回调中就可以根据这个参数去加载指定文件

 

不同加载方式分析:

  1. 直接使用DoString方式加载字符串,开发调试时可以使用
  2. 使用require方式加载,lua文件后缀需为txt,文件必须放在Resources目录下,否则无法加载到文件
  3. 自定义loader则可以把lua文件放在任意合法文件夹下,且文件后缀不用增加txt标识
posted @ 2020-02-24 15:20  骑驴看世界  阅读(1326)  评论(0编辑  收藏  举报