Lua 绑定:表与用户数据

发布于 2024-08-05 03:24:02 字数 63 浏览 3 评论 0原文

当为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

逆光下的微笑 2024-08-12 03:24:02

我建议返回用户数据。无论采用哪种方法,都必须有一个地方可以放置指针
到 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.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文