c# 部分
public class Test5Obj { public int i; private string str; public Test5Obj() { } public void PrintInt() { Debug.Log($"c# PrintInt:{i}"); } public void PrintStr() { Debug.Log($"c# PrintStr:{str}"); } }
public class Test5 : MonoBehaviour { private LuaEnv m_LuaEnv; void Start() { m_LuaEnv = new LuaEnv(); m_LuaEnv.AddLoader((ref string filePath) => { filePath = filePath.Replace('.', '/'); filePath = $"Assets/{filePath}.lua.txt"; var txtAsset = AssetDatabase.LoadAssetAtPath<TextAsset>(filePath); return Encoding.UTF8.GetBytes(txtAsset.text); }); m_LuaEnv.Global.Set("Test5MonoInst", this); m_LuaEnv.DoString("require('Lua.Test5')"); } void OnDestroy() { if (null != m_LuaEnv) m_LuaEnv.Dispose(); } public void DoPrint(Test5Obj obj) { obj.PrintInt(); obj.PrintStr(); } }
lua脚本:
c#函数参数为class或struct时,如果lua提供的参数值为table,xlua会利用table来创建class或struct对象(所有public field会用table的同名字段初始化)
Test5MonoInst:DoPrint({ i = 5, str = "abc" }) --i为public字段, 会被初始化; str为private字段, 不会被初始化
lua脚本:
table的函数,默认不会覆盖掉class或stuct的函数
local Test5Obj = {} Test5Obj.__index = Test5Obj function Test5Obj.new() local obj = { i = 6, str = "def" } setmetatable(obj, Test5Obj) return obj end function Test5Obj:PrintInt() print("PrintInt") end function Test5Obj:PrintStr() print("PrintStr") end local obj = Test5Obj.new() Test5Mono:DoPrint(obj)
标签:obj,filePath,c#,xlua,Test5Obj,lua,LuaEnv,public From: https://www.cnblogs.com/sailJs/p/18037410