问题
What I'm looking for is something like:
lua script
MY_ARRAY = {
00, 10, 54, 32,
12, 31, 55, 43,
34, 65, 76, 34,
53, 78, 34, 93
}
c code
lua_Number array[] = lua_getarray("MY_ARRAY");
Is this possible? Is there anything similar to make dealing with lua tables in C easier.
回答1:
You can write such function yourself! It shouldn't be too many lines. But it's better to use pointers than arrays, because they can point to any number of elements. The interface could be something like this:
lua_Number *values;
size_t nvalues;
values = luaGetNumbers("MY_ARRAY", &nvalues);
/* the number of values is now nvalues */
for (int i=0; i<nvalues; i++) {
/* do something with values[i] */
}
free(values);
And the implementation should use the following functions (from http://www.lua.org/manual/5.2/manual.html):
void lua_getglobal (lua_State *L, const char *name);
Pushes onto the stack the value of the global name.
void lua_gettable (lua_State *L, int index);
Pushes onto the stack the value t[k], where t is the value at the given valid index and k is the value at the top of the stack.
This function pops the key from the stack putting the resulting value in its place). As in Lua, this function may trigger a metamethod for the "index" event (see §2.4).
lua_Number lua_tonumberx (lua_State *L, int index, int *isnum);
Converts the Lua value at the given acceptable index to the C type lua_Number (see lua_Number). The Lua value must be a number or a string convertible to a number (see §3.4.2); otherwise, lua_tonumberx returns 0.
If isnum is not NULL, its referent is assigned a boolean value that indicates whether the operation succeeded.
void lua_len (lua_State *L, int index);
Returns the "length" of the value at the given acceptable index; it is equivalent to the '#' operator in Lua (see §3.4.6). The result is pushed on the stack.
来源:https://stackoverflow.com/questions/11662650/convert-lua-table-to-c-array