Skip to content

Instantly share code, notes, and snippets.

@jlj
Last active August 29, 2015 14:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jlj/9a9d4ce166092ba427ce to your computer and use it in GitHub Desktop.
Save jlj/9a9d4ce166092ba427ce to your computer and use it in GitHub Desktop.
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