xlua-C#访问lua中的table
using System.Collections;using System.Collections.Generic;using UnityEngine;using XLua;/** Author:W
* C#访问Lua中table
*/publicclassCSharpCallLua:MonoBehaviour{privateLuaEnv luaEnv;// Use this for initializationvoid Start (){
luaEnv =newLuaEnv();
luaEnv.DoString("require 'CSharpCallLua'");//方式1:通过映射类或结构体访问lua中的table//特点:通过值拷贝的形式,因此会比较耗费性能;另外,各自修改值,不会影响到对方Student student = luaEnv.Global.Get<Student>("Student");
Debug.Log("方式1 普通类或结构体:Name="+ student.Name +" Age="+ student.Age);
Debug.Log("===================================================");//方式2:通过接口访问lua中的table//特点:类似引用的方式,因此在C#中做修改,也会影响到lua中变量值IStudent student1 = luaEnv.Global.Get<IStudent>("Student");
Debug.Log("方式2 接口:Name="+student1.Name+" Age="+student1.Age);
student1.sum(1,4);
student1.sum2(5,6);
student1.sum3(7,8);
Debug.Log("===================================================");//方式3:通过Dictionary/List访问lua中的table//Dictionary只能访问到“key = value”的
Dictionary<string,object> Dict = luaEnv.Global.Get<Dictionary<string,object>>("DictAndList");foreach(string key in Dict.Keys){
Debug.Log("方式3:Dict字典="+ key+"-"+Dict);}//List只能访问到只有value的
List<object> Lists = luaEnv.Global.Get<List<object>>("DictAndList");foreach(object o in Lists){
Debug.Log("方式3:List集合= "+ o);}
Debug.Log("===================================================");//方式4:使用xlua自带通用luaTable映射类来访问lua中的table//特点:不需要生成代码,但是慢,比方式2慢一个数量级,不推荐使用LuaTable luaTable = luaEnv.Global.Get<LuaTable>("Student");
Debug.Log("方式4:LuaTabel类= Name-"+luaTable.Get<string>("Name"));}privatevoidOnDestroy(){if(luaEnv !=null)
luaEnv.Dispose();}/// <summary>/// 对应的映射类/// </summary>classStudent{publicstring Name;publicint Age;}}/// <summary>/// 对应的接口/// 注意:必须加上标签/// </summary>interfaceIStudent{string Name {get;set;}int Age {get;set;}voidsum(int a,int b);voidsum2(int a,int b);voidsum3(int a,int b);}lua脚本
Student ={ Name="WangLunQiang",
Age=35,
--函数定义方式1
sum= function(self,a,b)
print("sum = ",a+b)
end
}
--函数定义方式2:使用冒号,自动会赋值self
function Student:sum2(a,b)
print("sum2 = ",a+b)
end
--函数定义方式3;使用点,需要传入self自身参数
function Student.sum3(self,a,b)
print("sum3 = ",a+b)
end
DictAndList ={
Name="WangLunQiang",
Age=35,
eat = function()
print("eat")
end,
2,
4,
"W",
}运行结果截图如下:
页:
[1]