• 使用XLua在Unity中获取lua全局变量和函数


    1、Lua脚本 

    入口脚本

    1. print("OK")
    2. --也会执行重定向
    3. require("Test")

    测试脚本

    1. print("TestScript")
    2. testNum = 1
    3. testBool = true
    4. testFloat = 1.2
    5. testStr = "123"
    6. function testFun()
    7. print("无参无返回")
    8. end
    9. function testFun2(a)
    10. print("有参有返回")
    11. return a
    12. end

    2、C#脚本

    (1)获取全局变量

    1. public class L4 : MonoBehaviour
    2. {
    3. // Start is called before the first frame update
    4. void Start()
    5. {
    6. //自己编写的Lua管理器
    7. //初始化管理器
    8. LuaMgr.GetInstance().Init();
    9. //执行Main脚本(调用了Test脚本)
    10. LuaMgr.GetInstance().DoLuaFile("Main");
    11. //得到全局变量(只是复制到C#,改不了)
    12. int i = LuaMgr.GetInstance().Global.Get<int>("testNum");
    13. print(i);
    14. //修改全局变量
    15. LuaMgr.GetInstance().Global.Set("testNum", 2);
    16. i = LuaMgr.GetInstance().Global.Get<int>("testNum");
    17. print(i);
    18. }
    19. }

    执行结果

    (2)获取全局函数

    1. using XLua;
    2. public class L5 : MonoBehaviour
    3. {
    4. // Start is called before the first frame update
    5. void Start()
    6. {
    7. LuaMgr.GetInstance().Init();
    8. LuaMgr.GetInstance().DoLuaFile("Main");
    9. #region 无参无返回
    10. //第一种方法 通过 GetFunction方法获取(需要引用命名空间)
    11. LuaFunction function = LuaMgr.GetInstance().Global.Get("testFun");
    12. //调用 无参无返回
    13. function.Call();
    14. //执行完过后
    15. function.Dispose();
    16. #endregion
    17. #region 有参有返回
    18. //第一种方式 通过luafunction 的 call来访问
    19. LuaFunction function2 = LuaMgr.GetInstance().Global.Get("testFun2");
    20. Debug.Log("有参有返回值 Call:" + function2.Call(10)[0]);
    21. #endregion
    22. }
    23. }
  • 相关阅读:
    08数组-滑动窗口、HashMap
    网站如何才能不被黑,如何做好网络安全
    洛谷 P4752 Divided Prime
    Redis 学习笔记2
    知识问答产品利器:文本分段器实现自动知识加工
    docker安装minio,从入门到放弃
    【题解】同济线代习题一.8.1
    存储过程,游标,触发器
    【ARM AMBA AXI 入门 11 - AXI 总线 AWCACHE 和 ARCACHE 介绍】
    mybatis注解开发
  • 原文地址:https://blog.csdn.net/holens01/article/details/133771005