using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using XLua;
using System;
using System.IO;
namespace Tutorial
{
public class CSCallLua : MonoBehaviour
{
LuaEnv luaenv = null;
public class DClass
{
public int f1;
public int f2;
}
[CSharpCallLua]
public delegate int FDelegate(int a, string b, out DClass c, ref int x, ref string y);
void Start()
{
luaenv = new LuaEnv();
//TextAsset luaScript = Resources.Load<TextAsset>("hello");
//luaenv.DoString(luaScript.text);
luaenv.AddLoader(SelfDefineLoader);
luaenv.DoString("require 'hello'"); //使用requre 'xxxx'的方式,会触发自定义的loader
FDelegate f = luaenv.Global.Get<FDelegate>("f");
DClass d_ret;
int x = 0;
string y = string.Empty;
int f_ret = f(100, "John", out d_ret, ref x, ref y);
}
/// <summary>
/// 自定义的路径的加载器
/// </summary>
/// <param name="filepath"></param>
/// <returns></returns>
public byte[] SelfDefineLoader(ref string filepath)
{
filepath = Application.dataPath + "/XLua/Tutorial/CSharpCallLua/Resources/" + filepath + ".txt";
if (File.Exists(filepath))
{
return File.ReadAllBytes(filepath);
}
else
{
return null;
}
}
void OnDestroy()
{
luaenv.Dispose();
}
}
}
lua文件:
function f(a, b)
print('a', a, 'b', b)
return 1, {f1 = 1024}, 999, "hello,world"
end
补充1:
更新于2022.2.23
这里的自定loader方式,一定要注意lua源文件的编码个是,有时候,会出现这样的代码:
private byte[] CustomLoader(ref string filename)
{
string path = string.Format("StreamingAssets/lua/{0}.lua.txt", filename);
var text = File.ReadAllText(path, System.Text.Encoding.UTF8);
return System.Text.Encoding.UTF8.GetBytes(text);
}
这里在lua都是明文的情况下,是没有问题的。
但是,如果使用luac,将明文转成了字节码的话。
如果还是使用这个自定义的加载器的话,会出现
经过断点,发现读取内容然后再转码,则会出现上面的报错。
所以要改加载器:
private byte[] CustomLoader(ref string filename)
{
string path = string.Format("StreamingAssets/lua/{0}.lua.txt", filename);
//var text = File.ReadAllText(path, System.Text.Encoding.UTF8);
//return System.Text.Encoding.UTF8.GetBytes(text);
return Zeus.Core.FileSystem.VFileSystem.ReadAllBytes(path);
}
同事保证,明文的lua文件,要以utf8个的编码格式,这样就不会出错了。
当然,这里的luac,是使用xlua自己编出来的luac,如果5.3.5的lua代码是加固后的,那么luac也要在mac上进下编译之后,在进行转码的操作,这其中一个环节不对,lua执行就会出现错误。