lua-users home
lua-l archive

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


Hi!
I`m trying to get all table data from Lua script.

Script is simple, but I do not know key values - I want to get them in
runtime.
Script look like this (test.lua)
-------------------------
testArray={
a=1, b=2, c=3
};
-------------------------
And my code is
-------------------------
#include <iostream>
#include <stdlib.h>
#include <assert.h>

using namespace std;

extern "C" {
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
} 
lua_State *L;

int main(int argc, char *argv[])
{
  int i=0;
  int tIndex;
  lua_State *L = lua_open();
  assert(L);
// stack size=0
  luaopen_base(L);
  luaopen_io(L);
  luaopen_string(L);
  luaopen_math(L);
// stack size = 6, io add 3
  if (luaL_loadfile(L, "test.lua")|| lua_pcall(L, 0, 0, 0))
  {
     cout<<"\nCannot run file: "<<lua_tostring(L, -1);
  }    
  lua_getglobal(L, "testArray");
  if(!lua_istable(L,-1))
   {
    cout<<"\nError getting table\n";    
    lua_close(L); 
    exit(0);
   }
  tIndex=lua_gettop(L);
  lua_gettable(L,-1);
  lua_pushnil(L); // first key
  while (lua_next(L, tIndex) != 0)
  {
      cout<<"\n";
      cout<<"key has type="<<lua_typename(L, lua_type(L, -2));
      cout<<", value has type:"<<lua_typename(L, lua_type(L, -1));
      lua_pop(L, 1); 
  }
 lua_close(L); 
 system("PAUSE");       
 return 0;
}
----------------------------

I`m trying to proceed as in the reference manual (p 3.11 -
Manipulating tables), but I got "segfault" at the first lua_next()
call in while. What I`m doing wrong ?

I`m using Dev-CPP (mingw, gcc under windows). All examples work fine,
I can create/destroy C++ objects from Lua.... But I can not read
simple tables :(

-- 
Best regards,
 Sergey                          mailto:serj@dqteam.com