lua-users home
lua-l archive

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


Hi,
 
I intend to write a function that can take a table as input, but I afiled to pass the table parameter. Can someone help me?
 
For example,
 
/* Func(1, {key={1, 2, 3, 4}, key1={p1, p2, p3}, key2={{5, 6, 7, 8}, p4, p5, p6}}, 2);
   I'm able to pass Func(1, {key={1, 2, 3, 4}, key1={p1, p2, p3}}, 2);  */
 
bool Func(lua_State *L)
{
    int n = lua_gettop(L);
    if (n != 3)
         lua_error(L);
    int id = (int)lua_tonumber(L, 1);
    std::list<int> numberlist;
    std::map<std::string, vector<OwnStruct*> > pmap;
    if (!parse_parameter(L, id, 2, numberlist, pmap))
        luaL_error(L, "failed to parse parameter\n");
}
 
bool parse_pa( lua_State* L, int id, int i, const char *name, std::list<int>& numberlist, std::map<std::string, vector<OwnStruct*> >& pmap)
{
   if (lua_istable(L, i)) {
        lua_pushnil(L);
        while (lua_next(L, i)) {
                 if (lua_isnumber(L, -1)) {
                          int x = lua_tonumber(L, -1);
                          numberlist.push_back(x);
                 }
                 } else if (luaL_checkudata(L, -1, MYOWNTYPE)) {
                      p = reinterpret_cast<OwnStruct*>(lua_touserdata(L, -1));
                      std::vector<OwnStruct*> v;
                      v.push_back(p);
                      pmap[name] = v;
            } else if (lua_istable(L, -1)) {
                if (!parse_pa(L, vid, i, name, numberlist, pmap)) {
                    lua_pop(L, 2);
                    return  false;
                }
            } else {
                 lua_pop(L, 2);
                r eturn  false;
            }
            lua_pop(L, 1);
        }
        return true;
     }
     return false;
}
 
bool parse_parameter( lua_State* L, int id, int i, std::list<int>& numberlist, std::map<std::string, vector<OwnStruct*> >& pmap)
{
    if (parse_pa(L, id, i, "", numberlist, pmap))
      return true;
 
    lua_pushnil(L);
    while (lua_next(L, i)) { 
        if (!lua_isstring(L, -2)) {
            lua_pop(L, 2);
            return false;
        }
        const char *name = lua_tostring(L, -2);
        if (!parse_pa(L, id, i, name, numberlist, pmap)) {
            lua_pop(L, 2);
            return false;
        }
        lua_pop(L, 1);
    }
    return true;
}
 
Can anyone help me to find out how to parse Func(1, {key={1, 2, 3, 4}, key1={p1, p2, p3}, key2={{5, 6, 7, 8}, p4, p5, p6}}, 2); ?
Thanks a lot!
 
Andrew


Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now.