11.CSharp调用Lua-表映射到LuaTable
11.1 知识点
准备工作
初始化Lua管理器并调用Lua脚本
// 初始化Lua管理器,创建Lua脚本并在C#脚本调用
LuaManager.Instance.Init();
LuaManager.Instance.DoLuaFile("Lesson11_CSharp调用Lua_表映射到LuaTable");
给Lua脚本添加普通表
print('我是Lua脚本 Lesson11_CSharp调用Lua_表映射到LuaTable')
testClass = {
testInt = 6,
testBool = true,
testFloat = 6.66,
testString = "666",
testFun = function()
print("666666")
end,
testIntClass =
{
testIntClassInt = 999
},
testMoreInLuaInt = 6,
}
表映射到LuaTable
不建议使用LuaTable和LuaFunction
// 不建议使用LuaTable和LuaFunction,效率低
LuaTable testClass1 = LuaManager.Instance.Global.Get<LuaTable>("testClass");
公共成员
Debug.Log(testClass1.Get<int>("testInt")); // 6
Debug.Log(testClass1.Get<bool>("testBool")); // True
Debug.Log(testClass1.Get<float>("testFloat")); // 6.66
Debug.Log(testClass1.Get<string>("testString")); // "666"
testClass1.Get<LuaFunction>("testFun").Call(); // "666666"
类的嵌套
Debug.Log(testClass1.Get<LuaTable>("testIntClass").Get<int>("testIntClassInt")); // 999
Lua表中不存在的成员会报错
// Lua表中不存在的成员会报错
// Debug.Log(testClass1.Get<int>("testNoInLuaInt")); // 报错
使用LuaTable改变映射到的C#类会改变Lua原表中的值
testClass1.Set("testInt", 10000);
LuaTable testClass2 = LuaManager.Instance.Global.Get<LuaTable>("testClass");
Debug.Log(testClass1.Get<int>("testInt")); // 10000
使用完LuaTable需要释放,否则可能内存泄漏
testClass1.Dispose();
testClass2.Dispose();
11.2 知识点代码
Lesson11_CSharp调用Lua_表映射到LuaTable.lua
print('我是Lua脚本 Lesson11_CSharp调用Lua_表映射到LuaTable')
testClass = {
testInt = 6,
testBool = true,
testFloat = 6.66,
testString = "666",
testFun = function()
print("666666")
end,
testIntClass =
{
testIntClassInt = 999
},
testMoreInLuaInt = 6,
}
Lesson11_CSharp调用Lua_表映射到LuaTable
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
public class Lesson11_CSharp调用Lua_表映射到LuaTable : MonoBehaviour
{
void Start()
{
LuaManager.Instance.Init();
LuaManager.Instance.DoLuaFile("Lesson11_CSharp调用Lua_表映射到LuaTable");
#region 知识点一 表映射到LuaTable
//不建议使用LuaTable和LuaFunction 效率低
LuaTable testClass1 = LuaManager.Instance.Global.Get<LuaTable>("testClass");
//公共成员
Debug.Log(testClass1.Get<int>("testInt"));//6
Debug.Log(testClass1.Get<bool>("testBool"));//True
Debug.Log(testClass1.Get<float>("testFloat"));//6.66
Debug.Log(testClass1.Get<string>("testString"));//666
testClass1.Get<LuaFunction>("testFun").Call();//666666
//类的嵌套
Debug.Log(testClass1.Get<LuaTable>("testIntClass").Get<int>("testIntClassInt"));//999
//Lua表中不存在的成员 会报错
//Debug.Log(testClass1.Get<int>("testNoInLuaInt"));//报错
//使用LuaTable改变映射到的C#类会改变Lua原表中的值
testClass1.Set("testInt", 10000);
LuaTable testClass2 = LuaManager.Instance.Global.Get<LuaTable>("testClass");
Debug.Log(testClass1.Get<int>("testInt"));//10000
//使用完LuaTable需要释放 否则可能内存泄漏
testClass1.Dispose();
testClass2.Dispose();
#endregion
}
}
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 785293209@qq.com