Lua用户数据GC

发布于 2024-09-05 11:44:28 字数 656 浏览 1 评论 0原文

一段 Lua 用户数据是否可以保存对 Lua 对象的引用? (比如一张表,或者另一条用户数据?)。基本上,我想知道的是:

我可以以这样的方式创建一段用户数据吗?当 gc 运行时,用户数据可以说:“嘿!我持有对这些其他对象的引用,也标记它们。 ”

编辑:回应 lhf:

假设我有:

struct Vertex {
  double x, y, z;
}

struct Quaternion {
  double w, x, y, z;
}

现在,我可以做:

struct Foo {
  Vertex v;
  Quaternion q;
}

但假设我想要:

struct Bar {
  Vertex *v;
  Quaternion *q;
}

[即假设 Vertex &四元数确实是很大的用户数据]。

现在,假设我有一个 Lua 用户函数,它接受一个 userdata Vertex 和一个 userdata 四元数,并创建一个 userdata Bar (我不需要 userdata Foo,因为我想节省空间)——那么我需要以某种方式userdata Vertex*/Quaternion* 不进行 gc 处理。

Is it possible for a piece of Lua userdata to hold reference to a Lua object? (Like a table, or another piece of userdata?). Basically, what I want to know is:

Can I create a piece of userdata in such a way taht when the gc runs, the user data can say: "Hey! I'm holding references to these other objects, mark them as well."

EDIT: responding to lhf:

Suppose I have:

struct Vertex {
  double x, y, z;
}

struct Quaternion {
  double w, x, y, z;
}

Now, I can do:

struct Foo {
  Vertex v;
  Quaternion q;
}

but suppose instead I want:

struct Bar {
  Vertex *v;
  Quaternion *q;
}

[i.e. suppose Vertex & Quaternion are really big pieces of userdata].

Now, suppose I have a Lua user function that takes a userdata Vertex, and a userdata Quaternion, and creates a userdata Bar (I don't want a userdata Foo since I want to save the space) -- then I need somehow for the userdata Vertex*/Quaternion* to not be gc-ed.

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

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

发布评论

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

评论(2

不羁少年 2024-09-12 11:44:29

一段lua用户数据是否可以保存对lua对象的引用?

不可以。 userdata 不能保存指向另一个 Lua 对象的指针。如果您想使用用户数据来保持另一个 Lua 对象的活动状态,则必须使用弱表来实现。 Roberto 的书关于如何做到这一点的部分

Is it possible for a piece of lua user data to hold reference to a lua object?

No. A userdata can't hold a pointer to another Lua object. If you want to use a userdata to keep another Lua object alive, you have to do it using weak tables. Roberto's book as a section on how to do it.

淡水深流 2024-09-12 11:44:29

自从我用 lua 做任何事情以来已经有一段时间了。我认为如果引用的数据是由lua机器创建的,那么它会自行清理它。否则,您必须等待 C 代码中的 gc 回调并自行释放内存。

Been a while since I did anything with lua. I think that if the data referenced was created by the lua machine, then it will clean it up itself. Otherwise you must wait for the gc callback in your C code and free the memory yourself.

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