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.
lua_getfield
throw an error? – Egor Skriptunoff