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
tis 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
相关文章推荐
- lua math lib
- 【LintCode】Evaluate Reverse Polish Notation 逆波兰表达式求值
- Lua 学习备忘录3
- tengine安装lua
- Lua 学习备忘录2
- Lua脚本语言入门
- lua 的table排序
- CSLight研究院之和uLua的效率对比第一弹
- scikit-learn:3.5. Validation curves: plotting scores to evaluate models
- lua 文件读写
- 【转】Lua脚本语法说明简介
- lua os.date()参数
- Install and Evaluation of Yahoo's Kafka Manager
- [转]使用 C 编写 Lua 模块
- Lua 学习备忘录1
- Lua 资源热更新
- Lua 弱引用table
- Lua的面向对象——多重继承、私密性
- Lua的面向对象——类和继承
- Lua 基础:调用函数时用点号还是用冒号