简体   繁体   English

将Lua表转换为C数组?

[英]Convert Lua table to C array?

What I'm looking for is something like: 我正在寻找的是:

lua script lua脚本

MY_ARRAY = {
00, 10, 54, 32,
12, 31, 55, 43,
34, 65, 76, 34,
53, 78, 34, 93
}

c code c代码

lua_Number array[] = lua_getarray("MY_ARRAY");

Is this possible? 这可能吗? Is there anything similar to make dealing with lua tables in C easier. 是否有类似的东西可以更轻松地处理C中的lua表。

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 ): 实施应使用以下功能(来自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. 将值t [k]推入堆栈,其中t是给定有效索引处的值,k是堆栈顶部的值。

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一样,此函数可能触发“索引”事件的元方法(参见§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). 将给定可接受索引处的Lua值转换为C类型lua_Number(请参阅lua_Number)。 The Lua value must be a number or a string convertible to a number (see §3.4.2); Lua值必须是可转换为数字的数字或字符串(参见§3.4.2); otherwise, lua_tonumberx returns 0. 否则,lua_tonumberx返回0。

If isnum is not NULL, its referent is assigned a boolean value that indicates whether the operation succeeded. 如果isnum不为NULL,则为其引用对象分配一个布尔值,指示操作是否成功。


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). 它等同于Lua中的'#'运算符(参见§3.4.6)。 The result is pushed on the stack. 结果被推到堆栈上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM