如何为任意数量的Lua对象(表)实现(匿名)Lua回调函数?

发布于 2025-01-08 14:17:50 字数 363 浏览 4 评论 0原文

我在 Lua 中有一些“对象”,它们使用表来维护它们的数据和函数集。简单的例子:

obj = {func = function(self) print(self) end}

可能有任意数量的对象。

现在我有一个 C 函数 registerObject(obj) ,它应该以某种方式保留对该 Lua 对象(obj 表)的引用,以便稍后能够调用该特定对象的 func 函数(和其他函数)时间。这意味着我没有对象表的名称,我需要以某种方式保留对表本身的引用。

我怎样才能做到这一点? C++ 示例也可以接受,事实上 C 函数只是一个为每个 obj 创建一个 Objective-C 类的接口。

I have "objects" in Lua which use a table to maintain their set of data and functions. Simple example:

obj = {func = function(self) print(self) end}

There may be any number of objects.

Now I have a C function registerObject(obj) which should somehow keep a reference to that Lua object (obj table) in order to be able to call that particular object's func function (and others) at a later time. That means I don't have a name for the object's table, I somehow need to keep a reference to the table itself.

How can I make this work? C++ example also acceptable, in fact the C function is merely an interface that creates an Objective-C class for each obj.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

秉烛思 2025-01-15 14:17:50

Lua 表是通过引用传递的,因此它们实际上始终是“匿名”的,对它们的引用存储在变量中。我只是把你所有的“对象”放在一个表中
像这样:

objects={}
function registerObject(obj)
    objects[#objects+1]=obj
end
a={func=function(self) return(self.data) end, data='foo'}
b={func=function(self) return(self.data) end, data='bar'}
registerObject(a)
registerObject(b)
for k,v in pairs(objects) do
    print("Object",k,"data:",v:func())
end

您需要记住的一件事是,这会禁止收集这些表,因为对象表中始终存在对对象的引用,除非您显式删除它。这可能是也可能不是您想要的。如果您不希望对象表干扰垃圾回收,可以将元表中的 __mode 条目设置为“v”以表示弱值。这样,对对象表中对象的引用就不会被计算在内;如果对象表中的值是对该对象唯一剩余的引用,则该对象将被收集(请参阅使用 Lua 编程了解更多信息)。

Lua tables are passed by reference, so they are actually always "Anonymous", with a reference to them stored in a variable. I'd just put all your "objects" in a table
like this:

objects={}
function registerObject(obj)
    objects[#objects+1]=obj
end
a={func=function(self) return(self.data) end, data='foo'}
b={func=function(self) return(self.data) end, data='bar'}
registerObject(a)
registerObject(b)
for k,v in pairs(objects) do
    print("Object",k,"data:",v:func())
end

One thing you need to keep in mind is that this inhibits collection of those tables, since there always is a reference to the objects in the objects table, unless you explicitly delete it. This might or might not be what you want. If you do not want the objects table to interfere with garbage collection, you can set its __mode entry in the metatable to 'v' for weak values. That way, the references to the object in the objects table aren't counted; if the value in the objects table is the only remaining reference to the object, the object will be collected (See Programming in Lua for more info).

咋地 2025-01-15 14:17:50

注册表。我没什么可说的了

The registry. I have nothing more to say

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