Convert Lua table to C array?

大憨熊 提交于 2021-02-11 01:45:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!