unity教程三:学习xlua

加载lua脚本的三种方式

// 1.使 用luaEnv 全局环境中的成员方法DoString
_env = new LuaEnv();
_env.DoString("print('helloworld')");

// 2.使用Require加载Lua文件(常用的方式)
Lua env =new LuaEnv();
env.DoString("require HelloWorld") --helloWorld是个lua脚本文件

//3.自定义Loader
//这种方式就是直接使用Lua语言中的require来加载文件,可以看到实际上也是使用DoString,只是配合使用了lua里的require函数。
//实际使用的时候应该只DoString("require main")来加载一个main.lua文件,然后在main.lua中Require 其他脚本。
//优点:使用方便
//缺点:只能使用Resources与内置的路径的lua文件,不能自定义路径
//上面说了Require加载Lua文件的方式虽然方便但是会有所限制。那么现在就可以通过自定义loader来控制加载Lua文件的路径。
 void Start()
{
     _env = new LuaEnv();
     _env.AddLoader(CustomMyLoader);
     _env.DoString("require helloworld");
}

private byte[] CustomMyLoader(ref string fileName)
{
     string luaPath = Application.dataPath + "/LuaScripts/" + fileName + ".lua.txt";
     string strLuaContent = File.ReadAllText(luaPath);
     byte[] result = System.Text.Encoding.UTF8.GetBytes(strLuaContent);
     return result;
}

private void OnDestroy()
{
     _env.Dispose();
}

待添加

你可能感兴趣的:(unity教程三:学习xlua)