您的位置:首页 > 编程语言 > Lua

LUA脚本调用C场景,使用C API访问脚本构造的表

2015-07-30 23:41 671 查看

LUA调用C

lua解析中集成了一些系统服务, 故脚本中可以访问系统资源, 例如, lua脚本可以调用文件系统接口, 可以调用数学库,

但是总存在一些lua脚本中访问不到的系统服务或者扩展功能, 如果这些系统服务或者扩展功能是使用C语言实现,

那么可以, 使用lua库的对C库的封装方法, 将其中功能封装成lua 接口, 这样脚本就调用这些lua接口调用这些功能。

-------

这种情况,是以lua脚本作为宿主程序。

C调用LUA

另外一种场景,是C程序作为宿主程序, 调用LUA脚本, 例如将lua脚本做配置文件功能,

C语言调用 Capi运行lua脚本, 并取得其中配置的值。

本例结合第一种情况, 介绍C中如何获得lua脚本的表参数。

LUA C API

lua c api 介绍 : http://www.cnblogs.com/stephen-liu74/archive/2012/07/18/2433428.html
主要使用getfield接口访问表中某个key的值:


lua_getfield

[-0, +1, e]

void lua_getfield (lua_State *L, int index, const char *k);

Pushes onto the stack the value
t[k]
, where
t
is the value at the given valid index. As in Lua, this function may trigger a metamethod for the "index" event (see §2.8).


遍历表格的方法:
http://blog.csdn.net/chencong112/article/details/6908041 http://www.cnblogs.com/chuanwei-zhang/p/4077247.html
lua_getglobal(L, t);
lua_pushnil(L);
while (lua_next(L, -2)) {
/* 此时栈上 -1 处为 value, -2 处为 key */
lua_pop(L, 1);
}


lua_getglobal(L, t);
len = lua_objlen(L, -1);
for (i = 1; i <= len; i++) {
lua_pushinteger(L, i);
lua_gettable(L, -2);
/* 此时栈顶即为 t[i] 元素 */
lua_pop(L, 1);
}


DEMO

描述: 使用c封装了一个lua 接口, 此接口传入一个表, 在C中访问此表中某个key值。

-- temperature conversion table (celsius to farenheit)
require "test"

test.printTable({["a"]="aa"})


#include <stdlib.h>
#include <math.h>

#define lmathlib_c
#define LUA_LIB

#include "lua.h"

#include "lauxlib.h"
#include "lualib.h"

static int printTable (lua_State *L) {
printf("%s\n", "hello world");

int n = lua_gettop(L);

if ( n != 1 )
{
printf("%s\n", "printTable must has one arg");
}

if ( lua_istable(L, -1) )
{
lua_getfield(L, -1, "a");
printf("arg one table[a]=%s\n", lua_tostring (L, -1));
}
else
{
printf("%s\n", "printTable arg must be table");
}

return 0;
}

static const luaL_Reg testlib[] = {
{"printTable",   printTable},
{NULL, NULL}
};

LUALIB_API int luaopen_test (lua_State *L) {
luaL_register(L, "test", testlib);
return 1;
}


打印:


:~/share_windows/openSource/lua/lua-5.1.5$ lua ./test/test.lua
hello world
arg one table[a]=aa

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: