Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete memory allocated with lua_newuserdata

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?

like image 695
Objective Avatar asked Oct 18 '13 14:10

Objective


1 Answers

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:

  1. No need to free that memory in your C program. No need to worry about freeing it at all.

  2. Don't free that memory.

  3. Don't store a pointer to that memory in your C program and assume it is valid forever.

  4. 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.

like image 81
lhf Avatar answered Oct 12 '22 10:10

lhf