When does Lua gc memory allocated in C with
void *lua_newuserdata (lua_State *L, size_t size);
? When there is no reference in Lua pointing to it anymore or do I have to take care about deleting it?
Memory allocated with lua_newuserdata
is freed when there are no references to it inside Lua. This is how garbage collection works. There are important consequences:
No need to free that memory in your C program. No need to worry about freeing it at all.
Don't free that memory.
Don't store a pointer to that memory in your C program and assume it is valid forever.
If you want to use that pointer, make sure there is a reference to it in Lua.
In other words, after calling lua_newuserdata
you need to store that userdata value somewhere in Lua (a global variable, a table entry, a function upvalue) if you're going to use it later in your C program. Otherwise it may vanish after you return to Lua.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With