C调用Lua

C调用Lua的流程

1.创建一个Lua运行环境

2.将lua程序编译并载入虚拟栈

3.运行编译好的程序块

4.读取运行结果到虚拟栈中

5.对虚拟栈进行交互

 1 /*读取lua配置文件样例*/
 2 
 3 char fname[]="config";
 4 float width,height;
 5 //创建lua运行环境
 6 lua_State *L = luaL_newstate();  
 7 luaL_openlibs(L);
 8 
 9 //载入程序块并执行
10 if (luaL_loadfile(L, fname) || lua_pcall(L, 0, 0, 0))
11     error(L, "cannot run config. file: %s", lua_tostring(L, -1));
12 
13 //读取运行结果到虚拟栈中
14 lua_getglobal(L, "width");
15 lua_getglobal(L, "height");
16 
17 //和虚拟栈的交互
18 if (!lua_isnumber(L, -2))
19   error(L, "'width' should be a number\n");
20 if (!lua_isnumber(L, -1))
21   error(L, "'height' should be a number\n");
22 width  = lua_tointeger(L, -2);
23 height = lua_tointeger(L, -1);

读table的操作

1.lua_getglobal读取table到栈中

2.压入table的key

3.获取对应的value到栈中

写table的操作

1.栈中创建新table

2.压入table的key值

3.写入key对应的值

4.设置table键值

调用lua函数

1.将待调用函数压入栈

2.压入函数参数

3.使用lua_pcall调用

4.将调用从栈中弹出

posted @ 2014-09-13 22:10  再高一点  阅读(384)  评论(0编辑  收藏  举报