I want to make a C function that takes a lua table with strings as parameter, and the lua table does not have any keys, just values. How can I do this? I cannot figure it out. I did not find anything when I searched in google.
-
Did you take a look at Programming in Lua book? Especially the chapter 24hjpotter92– hjpotter922015-03-12 21:59:57 +00:00Commented Mar 12, 2015 at 21:59
-
@hjpotter92 No, I will take a look tomorrow, thanks for the suggestionErik W– Erik W2015-03-12 22:04:19 +00:00Commented Mar 12, 2015 at 22:04
-
2Do you know how tables work in Lua? (hint: they contain key/value pairs, there are no keys without values or values without keys)Stack Exchange Broke The Law– Stack Exchange Broke The Law2015-03-12 22:06:47 +00:00Commented Mar 12, 2015 at 22:06
-
@immibis But they have a default key when you don,t specify one yourself right?Erik W– Erik W2015-03-13 07:01:51 +00:00Commented Mar 13, 2015 at 7:01
-
@ErikW The default keys are consecutive integers starting from 1.Stack Exchange Broke The Law– Stack Exchange Broke The Law2015-03-13 07:47:11 +00:00Commented Mar 13, 2015 at 7:47
|
Show 2 more comments
1 Answer
The "default" keys in a table are consecutive integers starting from 1. This:
{"hello", "world"}
is the same as:
{[1] = "hello", [2] = "world"}
You cannot access these entries with lua_getfield, because that takes a string key. You can do it the "manual" way, with lua_pushnumber and lua_gettable. If L is your lua_State*, t is the index of the table on the stack and and k is the key, then:
lua_pushnumber(L, k);
lua_gettable(L, t);
should do the same thing as:
lua_getfield(L, t, k);
does for string keys. Note that if t is a relative index (a negative number), then because you're pushing another item onto the stack, you'll need to adjust it by 1.