lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


>How do you define "for which there are no other references"?

Lua's GC is mark-and-sweep: in each cycle, any value that is the value of
a global variable, table field, upvalue, stack value (including locals),
and perhaps some others that I forget right now, is marked. Every value that is
not marked is freed (or perhaps it's the other way around).

>I create a local variable that is a userdata pointer to an object in my c++
>code.  At the end of the block, how does lua know (or what determines) if
>there are no other references to that object?   

Lua doesn't know. It infers so, but only during the next GC cycle. The end of
a block does not trigger GC.

>Basically, I was hoping that the fact that the userdata is local indicates
>that the variable value would be collected once it's out of scope (so that
>the object the userdata points to gets deleted as well).  

Like I said, it does so, but only when GC is run.

>> collectgarbage()
>I find it strange that there is no C API function that does the same thing,
>only a lua library function.  What if the code lua is embedded in wants to
>force garbage collection?

Of course there is a C API function for that: it is used to implement
"collectgarbage":

static int luaB_collectgarbage (lua_State *L) {
  lua_setgcthreshold(L, luaL_opt_int(L, 1, 0));
  return 0;
}

So, to force GC at any time in C, call lua_setgcthreshold(L,0);

--lhf