[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: C API question - modifing table
- From: Michael Roth <mroth@...>
- Date: Wed, 11 Aug 2004 12:58:31 +0200
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Dmitry Samersoff wrote:
| I can add new value to table before iterate it,
| but code below doesn't work where is my mistake ?
There are three possible problems:
| /* table is in the stack at index `t' */
a.) Maybe, your stack index 't' is a relative index. This won't work
with your loop. Make sure, 't' is absolute.
| lua_pushnil(L); /* first key */
| while (lua_next(L, t) != 0)
| {
| /* `key' is at index -2 and `value' at index -1 */
| const char *key = lua_tostring(L, -2);
b.) The Lua manual states: "While traversing a table, do not call
lua_tostring directly on a key, unless you know that the key is actually
a string. Recall that lua_tostring changes the value at the given index;
this confuses the next call to lua_next."
| const char *val = lua_tostring(L, -1);
| cerr << "Key: " << key << " Val:" << val << endl;
| lua_pushstring(L,key);
c.) You fill up the stack because you leave every key value pair on the
stack. The Lua manual states: "When you interact with Lua API, you are
responsible for controlling stack overflow."
Either, pop the old value and don't push a new key, or make sure the
stack will grow using lua_checkstack() before you push a new key.
An example of your loop that should work. It will keep the key and
values on the stack.
~ /* somewhere in your code, push your table and
~ get the absolute index of it after you pushed it */
~ int t = lua_gettop(L);
~ /* first key */
~ lua_pushnil(L);
~ /* iterate, leave k,v pairs on stack */
~ while (lua_next(L, t))
~ {
~ /* make sure the stack is large enought for the
~ next iteration and push a copy of the unmodified
~ key for usage in the next iteration */
~ lua_checkstack(L, 2);
~ lua_pushvalue(L, -2);
~ /* convert the key and value to a string. this is
~ save because we copied the key earlier to the top
~ of the stack */
~ const char *key = lua_tostring(L, -3); /* Note: index changed */
~ const char *val = lua_tostring(L, -2);
~ cerr << "Key: " << key << " Val:" << val << endl;
~ }
~ /* If the loop terminates, lua_next() popped the copy of
~ the last key. Only key value pairs are left on the stack. */
The above code is untested. Maybe it contains errors and bugs. ;-)
-----BEGIN PGP SIGNATURE-----
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org
iD8DBQFBGfvWSIrOxc3jOmoRApdbAJ0fD0gaLqn4nNBIMnK7Cns06PQ3UgCgvnEt
q3XB1UgM5znCmqUGUjHKL4w=
=V1kV
-----END PGP SIGNATURE-----