Search code examples
lualua-api

Is it harmless to luaL_unref twice?


When referencing a value like so:

lua_pushnumber(L, 1);
ref = luaL_ref(L, LUA_REGISTRYINDEX);

Is it harmless to unreference ref multiple times or will this cause problems? i.e. is it harmless to call luaL_unref(L, LUA_REGISTRYINDEX, ref) multiple times for the code above or must there be only one luaL_unref call for each luaL_ref call?


Solution

  • It must be exactly one luaL_unref.
    Lua saves unrefed indices in a linked list for later reusing by luaL_ref.
    Unrefing the same index twice will lead to getting later this index twice from luaL_ref. This means you will overwrite your data previously refed.
    See https://www.lua.org/source/5.4/lauxlib.c.html#luaL_unref