lua-users home
lua-l archive

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


hi,
here is a snippet that i use in one of my programs.
  if(lua_istable(L,-2)) {
                                lua_settop(L,-2);
                                int index=-2;
                                lua_pushnil(L);
                                int key; double value;
                                while(lua_next(L,index) != 0) {
                                        if(!lua_isnumber(L,-2) ||
!lua_isnumber(L,-1)) E("[ERR] C:set_lib_data - invalid key,value
pair\n")
                                        else {
                                                key =
(int)lua_tonumber(L,-2); value = lua_tonumber(L,-1);
                                                M("[INFO] key: " <<
key << " value: " << value << endl)
                                        }
                                        lua_pop(L,1);
                                }
                                lua_pushnumber(L,1);
                        }else { E("[ERR] C:set_lib_data - invalid
argument 2\n") }

hope this helps.

-Abhinav

On Wed, Apr 9, 2008 at 7:01 AM, Eugen-Andrei Gavriloaie
<shiretu@gmail.com> wrote:
> Hi,
>
>  It might sound stupid, but it seems that I can't find a way to iterate
> through a table in c++. Suppose we have a table pushed onto the stack (lua
> calls a c++ function and passes all the parameters using a table: key/value
> pairs). How do I iterate on that table (present on the top of stack) in c++?
> I need both elements (key and value).
>
>  Please don't make fun of me now because I think I'll try to scratch with my
> left on the right side of my head .... :)
>
>  One approach would be to globalize the table from the stack by giving it a
> name using lua_setglobal and after that evaluate a generated lua script like
> this:
>
>  for k,v in pairs(_some_random_name) do
>
> call_another_cpp_function_that_handles_only_one_row_in_the_table(k,v)
>  end
>
>  evaluation is made using lua_loadstring()/lua_pcall()
>
>  After this, we can use lua_setglobal again to set `_some_random_name` to
> nil and make the table available for GC.
>
>  But this is a huuuuge implementation overhead IMHO, because you must keep a
> state in c++ outside the function
> call_another_cpp_function_that_handles_only_one_row_in_the_table (store the
> key/value pair (now present on the stack like 2 distinct elements, easy to
> pick up) into a more c++ manageable form like a vector or a map). Is there
> another better solution to this problem?
>
>  Thank you
>