Lua 绑定:表与用户数据
当为 C++ 类创建 Lua 绑定时,我应该返回表还是用户数据对象?
有谁知道每种方法的优缺点?
When making Lua bindings for C++ classes, should I return tables or userdata objects?
Does anyone know any of the pros and cons for each method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议返回用户数据。无论采用哪种方法,都必须有一个地方可以放置指针
到 C++ 数据,或者实际的 C++ 数据本身,并且无处可去
用桌子来做这件事是安全的。
在某些情况下返回表是有意义的,因为它们可以
在 Lua 中用额外的属性进行“注释”,而无需做任何事情
任何额外的东西来支持这一点。不幸的是C++对象指针
必须去某个地方,而且没有地方可以去其他地方
比表本身中的实际条目。
这对于它来说并不是一个非常安全的地方。可以通过Lua找到
代码,并删除或替换。这可能是偶然的,也可能是
目的,其实并不重要。
因此,我的偏好是返回用户数据对象。他们可以是
如果真的必须坚持的话,它们就像桌子一样工作,但它们
还有一个“秘密”区域(实际的用户数据本身),其中 C++
可以存储对象指针,防止被 Lua 代码覆盖。
(用户数据对象还有一个“环境”指针,这是另一个
存储特定于对象的数据的地方。与用户数据有效负载一样
就其本身而言,Lua 代码无法访问该值并且不会被损坏
那样。)
I recommend returning userdata. Regardless of approach, there has to be somewhere to put the pointer
to the C++ data, or the actual C++ data itself, and there's nowhere
safe to do this with a table.
Returning tables would make sense in some situations, because they can
be 'annotated' in Lua with extra attributes without one's having to do
anything extra to support this. Unfortunately the C++ object pointer
has to go somewhere, and there's nowhere sensible for it to go other
than an actual entry in the table itself.
This is not a very safe place for it to go. It can be found by Lua
code, and removed or replaced. This could be by accident, or on
purpose, it doesn't really matter.
My preference therefore is to return userdata objects. They can be
made to work like tables if one really must insist upon that, but they
also have a "secret" area (the actual userdata itself) where the C++
object pointer can be stored, safe from overwriting by Lua code.
(Userdata objects also have an "environment" pointer, which is another
place to store object-specific data. As with the userdata payload
itself, this value is inaccessible to Lua code and can't be damaged
that way.)