Registering Callbacks(注册lua c函数)
函数原型
作为一种替代机制 lua stack 是通过LuaStack类提供的
LuaPlus的回调函数使用了一种简单的函数机制 可以让全局函数 静态函数 非虚成员函数 与虚成员函数 成为回调函数
下面是一个示例 例子很简单就不注释了 (唯一需要注意的是 LuaStack args(state);)
使用 Register() 函数注册回调函数.
LuaObject 提供了几种重载的 Register() 函数:
Registering Object Dispatch Functors(注册一个c++类到lua)
虽然Register() 可以注册 c++类成员函数 但是他的第二个参数需要提供一个类对象
但是内部调用成员函数时候 this指针是一个常量 所以 Register()函数不是适合镜像c++类到lua中
this指针的问题 是通过 RegisterObjectFunctor() 函数解决的
官方文档原文
Even though Register()
can dispatch to C++ member functions, it
uses a 'this' pointer as provided by the second argument passed to the
function. The 'this' pointer is constant, and Register()
is not
suited for mirroring class hierarchies in Lua.
The solution to the 'this' pointer issue is through
RegisterObjectFunctor()
. It is a specialized form of
Register()
where a 'this' pointer isn't provided during the closure
registration. Instead, it is retrieved from either the calling userdata or the
calling table's __object
member, which must be a full or light
userdata.
下面 是实现2个c++类到lua的例子
Registering Functions Directly(直接注册普通函数)
LuaPlus通过RegisterDirect() 可以直接注册c++函数
以这种方式注册的函数 函数可以是任何形式的 内部会自动进行函数参数的类型检查
如果lua调用函数 传入的参数无效 则触发 luaL_argassert 导致调用失败
例如 state->DoString("print(Add(10, 'Hello'))"); 这样就导致失败了
全局函数可以这样注册 而成员函数也同样可以这样注册
直接注册的函数在目前版本中最多只支持7个参数
Object Dispatch to Directly Called C++ Member Functions(注册普通c++成员函数)
官方文档原文
Even though RegisterDirect()
can dispatch directly to C++ member
functions, it uses a 'this' pointer as provided by the second argument passed to
the function. The 'this' pointer is constant, and RegisterDirect()
is not suited for mirroring class hierarchies in Lua.
The solution to the 'this' pointer issue is through
RegisterObjectDirect()
. It is a specialized form of
RegisterDirect() where a 'this' pointer isn't provided during the closure
registration. Instead, it is retrieved from either the calling userdata or the
calling table's __object
member, which must be a full or light
userdata. The techniques presented in this section mirror closely the
RegisterObjectFunctor()
description above.
使用上一个注册c++对象的那个示例
向metatable内直接注册普通的c++成员函数
测试
Unregistering Callbacks(撤销已经注册到lua内的对象)
注销回调非常简单 只需将其设置为nil
globalsObj.SetNil("LOG");