lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



On10.04.2012 04:51, James Norton wrote:


lineSetup() is a C function created by factoring out common setup code:

void lineSetup(lua_State *L){
    GeminiLine *line = [[GeminiLine allocinitWithLuaState:L];
    GeminiLine **lLine = (GeminiLine **)lua_newuserdata(L, sizeof(GeminiLine *)); 
    *lLine = line;
    
    luaL_getmetatable(L, GEMINI_LINE_LUA_KEY);
    lua_setmetatable(L, -2);
    (...)

}
int luaopen_display_lib (lua_State *L){
    // create meta tables for our various types /////////

    

    // lines
    luaL_newmetatable(L, GEMINI_LINE_LUA_KEY);
    lua_pushvalue(L, -1);
    luaL_setfuncs(L, line_m, 0);

    

    

    /////// finished with metatables ///////////

    

    // create the table for this library and popuplate it with pointers to our functions
    luaL_newlib(L, displayLib_f);

    

    return 1;
}
-(void)createGlobal {
    lineSetup(L);

    

    // create an entry in the global table
    lua_setglobal(L, "Runtime");
    // clear the stack
    lua_pop(L, lua_gettop(L));
}

test.lua:7: attempt to index global 'x' (a userdata value)

My question is, why does line 4 work correctly, while line 7 complains about the global being userdata?  What is the difference between the = assignment on line 3 and the lua_setglobal in my Objective C code?

Thanks in advance for any suggestions.

-James


I don't think there is any difference how metatables are invoked in this two cases, actually if you didn't declared "line" as local than it is a global as well.
I think that the problem lies in the order in which createGlobal and luaopen_display_lib is called. You have to make sure that luaopen_display_lib is called before createGlobal otherwise the  luaL_getmetatable in lineSetup will get you a nil value. This would cause the global "Runtime" to have no metatable. If a userdata has no metatable with the function __newindex set you will exactly get the error message you have.

--
Thomas