开发者

Lua userdata gc

开发者 https://www.devze.com 2023-01-03 03:26 出处:网络
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:

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: respond开发者_如何转开发ing 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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消