[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: passing lua table from c++ to lua script
- From: Kevin Martin <kev82@...>
- Date: Sun, 20 May 2012 13:12:30 +0100
On 20 May 2012, at 12:49, Maha Akkari wrote:
> ! I have one more question , how can C fecth the table from lua ? I edited the Lua script to return t. so up to this point, lua pushed t onto the stack. how can C take it ?
So, you call the script with lua_pcall I take it?
The third argument of lua_pcall is the number of return values you expect. Set this to one. Then after the pcall, the top value on the stack will be your return value (or nil if you didn't return anything). You can then use lua_gettable/lua_next/etc to do what you want with it.
> I read another thread tackling this question, but i couldnt understand a word of the solution.
Here is some of our code to read a lua table produced in a script. The difference is we set a global variable called solution and access it with lua_getglobal instead of returning the table. The table has a set of string keys which hold another table with two entries, carerid and time, both strings. Hope it helps,
Thanks,
Kev
> lua_State *l = luaL_newstate();
> if(luaL_loadstring(l, luaData.c_str()) != LUA_OK) {
> luaOE_throwerror(l, "Couldn't compile solution ");
> }
> if(lua_pcall(l, 0, 0, 0) != LUA_OK) {
> luaOE_throwerror(l, "Could execute solution ");
> }
> lua_getglobal(l, "solution");
> if(lua_type(l, 1) != LUA_TTABLE) {
> throw std::runtime_error("Solution not found");
> }
>
> for(int visitnum = 0;visitnum != lp.data->vm.count();++visitnum) {
> std::string curVisitID = lp.data->vm[visitnum].id;
>
> //find the visitid table
> lua_pushstring(l, curVisitID.c_str());
> lua_gettable(l, -2);
> if(lua_type(l, -1) != LUA_TTABLE) {
> throw std::runtime_error("visitID index not table");
> }
>
> //get the carer id, continue loop if not set
> lua_pushstring(l, "carerid");
> lua_gettable(l, -2);
> if(lua_type(l, -1) == LUA_TNIL) {
> //this is an unallocated visit
> lua_settop(l, 1);
> continue;
> }
> assert(lua_type(l, -1) == LUA_TSTRING);
> std::string curCarerID = lua_tostring(l, -1);
> lua_pop(l, 1);
>
> //get the time
> lua_pushstring(l, "time");
> lua_gettable(l, -2);
> assert(lua_type(l, -1) == LUA_TSTRING);
> std::string curTime = lua_tostring(l, -1);
> lua_pop(l, 2);