Quick Links: Download Gideros Studio | Gideros Documentation | Gideros Development Center | Gideros community chat | DONATE
Code Snippet : Convert a Lua table to NSMutableDictionary — Gideros Forum

Code Snippet : Convert a Lua table to NSMutableDictionary

SatheeshJMSatheeshJM Member
edited June 2012 in Code snippets
A small utility function which converts a lua table to NSMutableDictionary
 
NSMutableDictionary* luaTableToDictionary(lua_State* L,int stack_index)
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
 
    //  STACK  { Table }
 
    lua_pushnil(L);
    //  STACK  { Table      Nil     }
 
 
    while (lua_next(L, stack_index) != 0) {
 
        //  STACK  { Table      key     Value   }
 
 
        id key = nil;
        switch(lua_type(L,-2))  {
            case LUA_TNUMBER: {
                int value = lua_tonumber(L, -2);
                NSNumber *number = [NSNumber numberWithInt:value];
                key = number;
                break;
            }
            case LUA_TSTRING: {
                NSString *value = [NSString stringWithUTF8String:luaL_checkstring(L, -2)];
                key = value;
                break;
            }    
 
        }
 
 
        id value = nil;
        switch (lua_type(L, -1)) {
            case LUA_TNUMBER: {
                int val = lua_tonumber(L, -1);
                NSNumber *number = [NSNumber numberWithInt:val];
                value = number;
                break;
            }
            case LUA_TBOOLEAN: {
                int val = lua_toboolean(L, -1);
                NSNumber *number = [NSNumber numberWithBool:val];
                value = number;
                break;
            }
            case LUA_TSTRING: {
                NSString *val = [NSString stringWithUTF8String:luaL_checkstring(L, -1)];
                value = val;
                break;
            }
            case LUA_TTABLE: {
                NSMutableDictionary *dict = luaTableToDictionary(L,stack_index+2);
                value = dict; 
                break;
            }
            default : {
                lua_pop(L, 1);
                continue;
            }
        }
        [dict setObject:value forKey:key];
        lua_pop(L, 1);
 
    }
 
 
    return dict;
}

Likes: gorkem, atilim

+1 -1 (+2 / -0 )Share on Facebook

Comments

Sign In or Register to comment.