error when accessing arrays as tables

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

error when accessing arrays as tables

Roman Vanicek
Hi all,

I have a problem when I want to access array as a table through C API.
Please consider this code:

in lua> enum = { 'one', 'two', 'three' };

in c >
lua_getglobal( L,"enum" );
lua_pushnil(L);
while( lua_next(L,1) ) {
    key = lua_tostring(L,-2);
    val = lua_tostring(L,-1);
    lua_pop(L,1);
}

First itertion gives me good results (ie. key/val = 1/one), but second
iteration is terminated in lua_next (application falls down).

If I try to access the fields via lua_rawgeti(L,1,i) it works fine.

Could you please give me a hand on this?

Thank you
Roman Vanicek

XTG Systems, s.r.o.
[hidden email]




Reply | Threaded
Open this post in threaded view
|

Re: error when accessing arrays as tables

Luiz Henrique de Figueiredo
>lua_getglobal( L,"enum" );
>lua_pushnil(L);
>while( lua_next(L,1) ) {
>    key = lua_tostring(L,-2);
>    val = lua_tostring(L,-1);
>    lua_pop(L,1);
>}
>
>First itertion gives me good results (ie. key/val = 1/one), but second
>iteration is terminated in lua_next (application falls down).

key = lua_tostring(L,-2) converts the object at -2 to a string; it used
to be a number, and this messes up the information that lua_next needs.

This is unfortunate. We'll try to improe this in 4.1.

You have to do something like this:
	val = lua_tostring(L,-1);
	lua_pushvalue(L,-2);
	key = lua_tostring(L,-1);
	lua_pop(L,2);

--lhf