将Lua表转换为C数组? [英] Convert Lua table to C array?

查看:182
本文介绍了将Lua表转换为C数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找的东西是这样的:

What I'm looking for is something like:

lua脚本

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

c代码

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

这可能吗?有什么类似的方法可以使在C语言中处理lua表变得更容易.

Is this possible? Is there anything similar to make dealing with lua tables in C easier.

推荐答案

您可以自己编写这样的函数!不应有太多行.但是,使用指针比使用数组要好,因为它们可以指向任意数量的元素.界面可能是这样的:

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);

该实现应使用以下功能(来自 http://www.lua.org/manual/5.2/manual.html ):

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);

将值t [k]推入堆栈,其中t是在给定有效索引,k是堆栈顶部的值.

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.

此函数从堆栈中弹出键,并放置结果值代替它).如在Lua中一样,此功能可能会触发索引"事件(请参阅第2.4节).

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);

将给定可接受索引处的Lua值转换为C类型lua_Number(请参阅lua_Number).Lua值必须是数字或可转换为数字的字符串(请参见第3.4.2节);否则,lua_tonumberx返回0.

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.

如果isnum不为NULL,则为其引用对象分配一个布尔值,该值指示操作是否成功.

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);

以给定的可接受索引返回值的长度";这是等效于Lua中的#"运算符(请参见第3.4.6节).结果是推入堆栈.

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.

这篇关于将Lua表转换为C数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆