luaplus 与官方文档慢慢扯(五)

本文详细介绍了如何使用LuaPlus库在Lua脚本中注册和调用C++函数、成员函数以及如何直接注册普通函数。同时,展示了如何通过RegisterObjectFunctor和RegisterObjectDirect函数将C++类映射到Lua环境中,并通过示例代码演示了注册过程及测试方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

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的例子

 

 

 

上面的obj1 和 obj2 是作为  userdata 然后设置它的metatables 的方法创建的 
另一种方法是将代表的c++对象的tuserdata作为表的成员 __object
 

 

 

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");

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值