[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: traversing nested tables in C
- From: "Grisha" <grisha@...>
- Date: Wed, 16 Jun 2004 11:52:59 +0400
Hi, Tassilo
When you traverse nested table, you call walk(L, -1), so your walk function
does this:
void walk (L, -1) {
lua_pushnil(L); // now nil is at -1 position !!!!
printf("idx=%i\n", -1);
while (lua_next(L, -1) != 0) { // ERROR: iterating nil value
print_pair(L);
lua_pop(L, 1);
}
}
Best Regards,
Grisha
----- Original Message -----
From: "Tassilo von Parseval" <tassilo.von.parseval@rwth-aachen.de>
To: "Lua list" <lua@bazar2.conectiva.com.br>
Sent: Wednesday, June 16, 2004 11:44 AM
Subject: traversing nested tables in C
> Hi there,
>
> I am currently experiencing unpleasant segfaults when recursively
> traversing Lua tables. This is the Lua function whose return value I'd
> like to traverse:
>
> function foo(a)
> local table = { x="a", y="a", z="a"}
> local table2 = { 1, 2 }
> table["4"] = table2
> return table
> end
>
> The corresponding C-code:
>
> #define KEY -2
> #define VAL -1
>
> void walk (lua_State *, int);
>
> void
> print_pair (lua_State *L) {
>
> switch (lua_type(L, KEY)) {
> case LUA_TNUMBER:
> Warn("key: %i\n", lua_tonumber(L, KEY));
> break;
> case LUA_TSTRING:
> Warn("key: %s\n", lua_tostring(L, KEY));
> }
>
> switch (lua_type(L, VAL)) {
> case LUA_TNUMBER:
> printf("val: %i (number)\n", lua_tonumber(L, VAL));
> break;
> case LUA_TSTRING:
> printf("val: %s (string)\n", lua_tostring(L, VAL));
> break;
> case LUA_TTABLE:
> walk(L, VAL);
> break;
> default:
> Warn("val: other\n");
> }
> }
>
> void walk (lua_State *L, int idx) {
> lua_pushnil(L);
>
> printf("idx=%i\n", idx);
> while (lua_next(L, idx) != 0) {
> print_pair(L);
> lua_pop(L, 1);
> }
> }
>
> This yields the output:
>
> idx=1
> key: y
> val: a (string)
> key: x
> val: a (string)
> key: z
> val: a (string)
> key: 4
> idx=-1
> key: 0
> val: 0 (number)
> Segmentation fault (core dumped)
>
> Are there some special steps I have to take when descending into a
> nested table thusly? If so, I suppose it would have to happen in the
> LUA_TTABLE case of print_pair(), but I don't know which.
>
> Thanks for any help,
> Tassilo
> --
>
$_=q#",}])!JAPH!qq(tsuJ[{@"tnirp}3..0}_$;//::niam/s~=)]3[))_$-3(rellac(=_$({
>
pam{rekcahbus})(rekcah{lrePbus})(lreP{rehtonabus})!JAPH!qq(rehtona{tsuJbus#;
>
$_=reverse,s+(?<=sub).+q#q!'"qq.\t$&."'!#+sexisexiixesixeseg;y~\n~~dddd;eval
>