2

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.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
anon
  • 41,035
  • 53
  • 197
  • 293
  • 1
    It seems convoluted. Why do you want to do this? – lhf Jun 14 '10 at 00:49
  • @lhf: does the above edit make sense? – anon Jun 14 '10 at 08:43
  • 1
    That's a different question now. The short answer is not to mix two styles of memory management: explicit in C vs automatic in Lua. See Norman's answer. – lhf Jun 14 '10 at 09:57
  • How is that a different question? The point is that "Bar" now needs to say -- hey, this Vertex*/Quaternion* I'm pointing to, in the lua heap, also needs to be marked. – anon Jun 14 '10 at 23:54

2 Answers2

4

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.

Norman Ramsey
  • 198,648
  • 61
  • 360
  • 533
  • "Strong tables" are tables where key & value are checked when gc-ing. How does weak tables factor in with userdata? Can you explain more? – anon Jun 14 '10 at 08:38
  • 1
    You put the userdata in the table along with the Lua value(s) that you're trying to keep alive. Roberto's book is online and explains it all. – Norman Ramsey Jun 14 '10 at 17:10
  • Why would I use a weak table instead of a strong table then? – anon Jun 14 '10 at 23:55
  • Because when the GC runs, if the weak table is the only reference, your userdata will be collected, and it will then stop keeping other objects alive. – Norman Ramsey Jun 15 '10 at 00:57
  • 1
    The clarification needed is then: Keep a mapping from userdata to 'other objects', with weak storage of the mapping keys. – u0b34a0f6ae Jun 19 '10 at 01:31
0

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.

Anthony
  • 12,177
  • 9
  • 69
  • 105