1、Lua脚本
入口脚本
- print("OK")
- --也会执行重定向
- require("Test")
测试脚本
- print("TestScript")
- testNum = 1
- testBool = true
- testFloat = 1.2
- testStr = "123"
-
- function testFun()
- print("无参无返回")
- end
-
- function testFun2(a)
- print("有参有返回")
- return a
- end
2、C#脚本
(1)获取全局变量
- public class L4 : MonoBehaviour
- {
- // Start is called before the first frame update
- void Start()
- {
- //自己编写的Lua管理器
- //初始化管理器
- LuaMgr.GetInstance().Init();
- //执行Main脚本(调用了Test脚本)
- LuaMgr.GetInstance().DoLuaFile("Main");
-
- //得到全局变量(只是复制到C#,改不了)
- int i = LuaMgr.GetInstance().Global.Get<int>("testNum");
- print(i);
- //修改全局变量
- LuaMgr.GetInstance().Global.Set("testNum", 2);
- i = LuaMgr.GetInstance().Global.Get<int>("testNum");
- print(i);
- }
- }
执行结果

(2)获取全局函数
- using XLua;
- public class L5 : MonoBehaviour
- {
- // Start is called before the first frame update
- void Start()
- {
- LuaMgr.GetInstance().Init();
- LuaMgr.GetInstance().DoLuaFile("Main");
-
- #region 无参无返回
- //第一种方法 通过 GetFunction方法获取(需要引用命名空间)
- LuaFunction function = LuaMgr.GetInstance().Global.Get
("testFun"); - //调用 无参无返回
- function.Call();
- //执行完过后
- function.Dispose();
- #endregion
-
- #region 有参有返回
- //第一种方式 通过luafunction 的 call来访问
- LuaFunction function2 = LuaMgr.GetInstance().Global.Get
("testFun2"); -
- Debug.Log("有参有返回值 Call:" + function2.Call(10)[0]);
- #endregion
- }
- }