Unity tolua调用C#中的自定义对象的方法
Unity:
定义一个类
using UnityEngine; public class TestLua_A { public int a = 1; public void TestFuncStr(string str) { Debug.Log("mStr :" + str); } public TestLua_A TestFuc(int a) { return new TestLua_A() { a = a,}; } }
wrap方法:
using System; using LuaInterface; public class TestLua_AWrap { public static void Register(LuaState L) { L.BeginClass(typeof(TestLua_A), typeof(Object)); L.RegFunction("TestFuncStr", TestFuncStr); L.RegFunction("New", _CreateTestLua_A); L.RegVar("a",get_a,set_a); L.EndClass(); } [MonoPInvokeCallback(typeof(LuaCSFunction))] static int get_a(IntPtr L) { object o = null; try { o = ToLua.ToObject(L, 1); TestLua_A obj = (TestLua_A)o; int ret = obj.a; LuaDLL.lua_pushinteger(L, ret); return 1; } catch (Exception e) { return LuaDLL.toluaL_exception(L, e, o, "attempt to index text on a nil value"); } } [MonoPInvokeCallback(typeof(LuaCSFunction))] static int set_a(IntPtr L) { object o = null; try { o = ToLua.ToObject(L, 1); TestLua_A obj = (TestLua_A)o; int arg0 = ToLua.CheckValue<int>(L, 2); obj.a = arg0; return 0; } catch (Exception e) { return LuaDLL.toluaL_exception(L, e, o, "attempt to index text on a nil value"); } } [MonoPInvokeCallback(typeof(LuaCSFunction))] static int TestFuncStr(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); TestLua_A obj = (TestLua_A)ToLua.CheckObject<TestLua_A>(L,1); string arg0 = ToLua.ToString(L,2); obj.TestFuncStr(arg0); return 0; } catch (Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallback(typeof(LuaCSFunction))] static int _CreateTestLua_A(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); TestLua_A obj = new TestLua_A(); ToLua.PushSealed(L,obj); return 1; } catch (Exception e) { return LuaDLL.toluaL_exception(L, e); } } }
Mono:
using UnityEngine; using System.Collections; using LuaInterface; public class Test : MonoBehaviour { LuaState lua; LuaFunction luaFun; // Use this for initialization void Start() { TestLua_A []testLua_A = new TestLua_A[1]; testLua_A[0] = new TestLua_A(); lua = new LuaState(); lua.Start(); LuaBinder.Bind(lua); Blind(lua); lua.DoFile(Application.streamingAssetsPath + "/TestLua/test_lua_button.lua"); luaFun = lua.GetFunction("test_array"); luaFun.BeginPCall(); luaFun.Push(testLua_A); luaFun.PCall(); Debug.Log(((TestLua_A)luaFun.CheckObject(typeof(TestLua_A))).a); luaFun.EndPCall(); } private void OnApplicationQuit() { if (luaFun != null) { luaFun.Dispose(); luaFun = null; } lua.Dispose(); } void Blind(LuaState lua) { lua.BeginModule(null); TestLua_AWrap.Register(lua); lua.EndModule(); } }
lua 脚本
local TestLua_A = TestLua_A function test_array( arr ) -- body print(arr[0].a) arr[0]:TestFuncStr("asfadsf") tmp = TestLua_A:New() tmp.a = 600 return tmp end
----------------------------OK-------------