1 字符串调用luaFunc :DoString
public class CallLuaFunction : MonoBehaviour
{
private string script =
@" function luaFunc(num)
return num + 1
end
test = {}
test.luaFunc = luaFunc
";
LuaFunction luaFunc = null;
LuaState lua = null;
string tips = null;
void Start ()
{
new LuaResLoader();
lua = new LuaState();
lua.Start();
DelegateFactory.Init();
lua.DoString(script);
//Get the function object
luaFunc = lua.GetFunction("test.luaFunc");
if (luaFunc != null)
{
int num = luaFunc.Invoke<int, int>(123456);
Debugger.Log("generic call return: {0}", num);
num = CallFunc();
Debugger.Log("expansion call return: {0}", num);
Func<int, int> Func = luaFunc.ToDelegate<Func<int, int>>();
num = Func(123456);
Debugger.Log("Delegate call return: {0}", num);
num = lua.Invoke<int, int>("test.luaFunc", 123456, true);
Debugger.Log("luastate call return: {0}", num);
}
lua.CheckTop();
}
void OnDestroy()
{
if (luaFunc != null)
{
luaFunc.Dispose();
luaFunc = null;
}
lua.Dispose();
lua = null;
}
int CallFunc()
{
luaFunc.BeginPCall();
luaFunc.Push(123456);
luaFunc.PCall();
int num = (int)luaFunc.CheckNumber();
luaFunc.EndPCall();
return num;
}
}
2 执行lua文件
lua = new LuaState();
lua.Start();
//如果移动了ToLua目录,自己手动修复吧,只是例子就不做配置了
string fullPath = Application.dataPath + "\\LuaFramework/ToLua/Examples/02_ScriptsFromFile";
lua.AddSearchPath(fullPath);
lua.DoFile("ScriptsFromFile.lua");
//lua.Require("ScriptsFromFile"); Require 只执行一次
lua.Collect();
lua.CheckTop();
3