一、要理解lua : 的用法机制:
1、函数声明时
function Main:Test1(go)
等价于
function Main.Test1(self, go)
即
function Main:Test1(go)
self.gb = go
self.init = true
end
等价于
function Main.Test1(self, go)
self.gb = go
self.init = true
end
也等价于
function Main.Test1(_mxxxx, go)
_mxxxx.gb = go
_mxxxx.init = true
end
假设Main.lua是这样的实现的
local Main = {}
function Main:Test1(go)
self.gb = go
self.init = true
end
function Main:Print()
print(self.gb)
end
return Main
2、访问时
假设 local m_main = require('Main') -- 即m_main是 Main结构的一个对象实例
m_main:Test1(3)
等价于
m_main.Test1(m_main, 3)
local ta = {}
ta:Test1(4) -- 这个肯定有错
但
m_main.Test1(ta, 4) -- 可以执行正常
m_main:Print() -- 能执行
ta:Print() -- 不能执行, ta 只有 2个成员 ta["gb"] 和 ta["init"] 没有叫Print的函数
m_main.Print(ta) --能执行, 输出ta["gb"] 的值
二、关于XLua 与 C#的交互方面问题:
1. 对于C#层面来说,也要理解静态函数或变量和非静态的区别, 静态的不需要new出对象直接用类名就能访问。
class A
{
public void test1() {}
public static void test2(){}
}
访问时
A.test1(); //不能访问,是错误的
A.test2(); //静态函数是可以访问的。
如果要访问test1()
则 需要 A类型的对象实例
比如
A a = new A();
a.test1();
2. 如果lua里访问C#,
假设 a 是 A的一个实例
a.test1() 访问会报错,
a.test2() 是可以的 CS.A.test2() 也是可以的,
对test1()访问要这样写:
a:test1()
等价于 a.test1(a)
( 应该也可以用 CS.A.test1(a) 访问)
原因,可以看 Wrap出来的代码, 就明白为啥要用冒号访问:
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _m_test1(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
A gen_to_be_invoked = (A)translator.FastGetCSObj(L, 1); //为啥要用冒号,就是这里,第一个参数需要一个A类的对象, 只有实例对象才可以访问非静态的函数
{
gen_to_be_invoked.test1();
return 0;
}
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _m_test2_xlua_st_(RealStatePtr L)
{
try {
{
A.test2( );
return 0;
}
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
}
3、至于C#访问lua
只要 前面lua的函数的参数理解到到位 就知道应该传哪些参数了。