xLua教程:https://github.com/Tencent/xLua/blob/master/Assets/XLua/Doc/XLua%E6%95%99%E7%A8%8B.md
xLua配置:https://github.com/Tencent/xLua/blob/master/Assets/XLua/Doc/configure.md
FAQ:https://github.com/Tencent/xLua/blob/master/Assets/XLua/Doc/faq.md
开始学习
private LuaEnv luaenv;
// Start is called before the first frame update
void Start()
{
luaenv = new LuaEnv();
luaenv.DoString("print('Hello World!')");
}
private void OnDestroy()
{
luaenv.Dispose();
}
在lua中调用C#中的方法
luaenv.DoString("CS.UnityEngine.Debug.Log('Hello World!')");
加载运行Lua源文件
在Resources文件夹中建一个 helloworld.lua.txt 文件
里面写着lua 程序
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
public class helloworld02 : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
TextAsset textAsset = Resources.Load<TextAsset>("helloworld.lua");
LuaEnv luaEnv = new LuaEnv();
luaEnv.DoString(textAsset.ToString());
luaEnv.Dispose();
}
通过内置的 loader 加载lua 源文件
luaenv.DoString(" require 'helloworld'"); //loader 会直接执行里面的代码
添加自定义的 loader 方法
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
public class defineloader03 : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
LuaEnv env = new LuaEnv();
env.AddLoader(MyLoader);
env.DoString("require 'helloworld'");
env.Dispose();
}
private byte[] MyLoader(ref string filepath)
{
print(filepath);
string s = "print(123)";
// 将字符串转成字节数组
return System.Text.Encoding.UTF8.GetBytes(s);
}
require 会将路径传递给每一个 loader 去执行,直到找到或者确定完全找不到为止(报异常)