Lua用户数据GC
一段 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不可以。 userdata 不能保存指向另一个 Lua 对象的指针。如果您想使用用户数据来保持另一个 Lua 对象的活动状态,则必须使用弱表来实现。 Roberto 的书关于如何做到这一点的部分。
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.
自从我用 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.