3

I would like to know what happens if I push the lightuserdata into the registry twice using the same key.

My Code:

MyData *x, *y; //let's say these are valid pointers

lua_pushstring(L, "my_data");
lua_pushlightuserdata(L, static_cast<void *>(x));
lua_settable(L, LUA_REGISTRYINDEX);

lua_pushstring(L, "my_data");
lua_pushlightuserdata(L, static_cast<void *>(y));
lua_settable(L, LUA_REGISTRYINDEX);

lua_pushstring(L, "my_data");
lua_gettable(L, LUA_REGISTRYINDEX);
MyData *data = static_cast<MyData *>(lua_touserdata(L, -1));

//would the data be x or y?

Would the previously pushed pointer (x) be replaced with the new one (y)?

ADDED: And is there a way to check the list of keys that are currently registered?

Henri Menke
  • 10,705
  • 1
  • 24
  • 42
Zack Lee
  • 2,784
  • 6
  • 35
  • 77
  • 1
    To check whether a field exists use: `lua_getfield(L, LUA_REGISTRYINDEX, "my_data"); if (!lua_isnil(L, -1)) { /* field exists, do something */ } lua_pop(L, 1);` – Henri Menke Aug 07 '18 at 00:25

1 Answers1

3

The Lua registry is an ordinary Lua table. Your code is equivalent to

registry.my_data = x
registry.my_data = y

So, yes, after these two lines the value of registry.my_data is the value of y.

lhf
  • 70,581
  • 9
  • 108
  • 149