Skip to content

Instantly share code, notes, and snippets.

@jlj
Last active August 29, 2015 14:14
Embed
What would you like to do?
A simple way of configuring Lua to accept the indexing of nil values
static int handleNilIndexing (lua_State* luaState)
{
return 0; // zero return values is equivalent to returning nil
}
lua_State* setupLua()
{
// Create the new lua state
lua_State* luaState = luaL_newstate();
// Set the indexing of nil as a valid operation
lua_pushnil(luaState); // <-- nil
lua_createtable(luaState, 0, 1); // <-- nil_metatable
lua_pushcfunction(luaState, handleNilIndexing); // <-- nil_field_handler
lua_setfield(luaState, -2, "__index"); // nil_metatable.__index = nil_field_handler
lua_setmetatable(luaState, -2); // nil.metatable = nil_metatable
lua_pop(luaState, 1); // -x- nil
return luaState;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment