Lua: garbage collection + userdata

Suppose the following situation:

typedef struct rgb_t {float r,g,b} rbg_t;

// a function for allocating the rgb struct
rgb_t* rgb(r,g,b) {
 rgb_t* c = malloc(sizeof(rgb_t));
 c->r=r;
 c->g=g;
 c->b=b;
 return c;
}

// expose rgb creation to lua
int L_rgb (lua_State* L) {
 rgb_t** ud = (rgb_t **) lua_newuserdata(L, sizeof(rgb_t *));
 *ud = rgb(lua_tonumber(L,1),lua_tonumber(L,2),lua_tonumber(L,3));
 return 1;
}

When the L_rgb function is called from Lua, two distributions occur. Lua allocates new user data, and the rgb constructor function allocates for the structure. What happens to userdata when a variable goes out of scope in Lua? If this is garbage collection, then what happens to the distribution of the structure?

+5
source share
2 answers

You have two approaches to this situation, and both can be applied to your specific case. Other cases lead you stronger to choose one over the other.

  • , , malloc(), , . , __gc , .

  • , lua_newuserdata() malloc(). __gc, Lua . , __index r, g b, .

.

+12

__gc . .

+2

All Articles