2
votes

I am passing a table { Value1=100, Value2=200, Value3=300, ...} from Lua to C. The following works great for my required values:

// Get the values from the table
lua_getfield(L, 2, "Value1");
lua_getfield(L, 2, "Value2");
lua_getfield(L, 2, "Value3");

const char *value_3 = luaL_checkstring(L, -1);
const char *value_2 = luaL_checkstring(L, -2);
const char *value_1 = luaL_checkstring(L, -3);

But I need to handle optional fields in the table, some of which may not be known at compile time - but will be known at run-time. Based on all my searches, I think I need to use a metatable to replace the __index method on the table operated on by lua_getfield() to return NIL rather than throwing an error if a particular key is not found. Then I could use luaL_checktype() to test for that.

I have used metatables with userdata with good success. But despite that, I really have no idea how to go about this.

1
Does lua_getfield throw an error?Egor Skriptunoff
Take the tour, read How to Ask, and minimal reproducible example. Almost perfect problem statement, except you need to actually ask a question.jwdonahue
No, but luaL_checkstring() would throw an error. Version 5.2 lua_getfield() was a void function. That changed in 5.3 and it now returns the type, including nil/0 if the key is not found in the table. I am using 5.3 library, but was referring to 5.2 Reference manual.Tim Mc

1 Answers

0
votes

No need to overcomplicate things. If you want to produce the default value in Lua, go for the metatable, but if you can get it in C, it is very easy. lua_getfield produces nil if the key cannot be found in the table, so you can compare its return value with LUA_TNIL to check if it returned nil (or lua_isnil if you use an older API). In that case, use your default value, or proceed with luaL_checkstring as usual.