转自:http://hi.baidu.com/bitbull/blog/item/bc27581eca1886f61bd5768e.html
问题概要: 用lua写了个函数,返回的是一个表.需要在C里对返回的表里元素做二次处理.
在C里我们可以通过lua_gettable()或者lua_rawget()来获取表里元素值,但使用这两个接口的前提是你得知道key,它才能给你value. 当然对于顺序下标倒无所谓,但恰巧这次我用到的是关联数组,下标是无规则字符串.这时候如何遍历出表里元素就是个问题.
lua_next()就成了比较合适的选择.画了下图对整个逻辑做了解释

t_idx = lua_gettop(L);
lua_pushnil(L);
while (lua_next(L, t_idx))
{
printf("============================\n");
it_idx = lua_gettop(L);
lua_pushnil(L);
while(lua_next(L, it_idx))
{
printf("%s\n", lua_tostring(L, -1));
lua_pop(L, 1);
}
lua_pop(L, 1);
}
本文仅起个抛砖引玉的作用, 实际上lua的栈逻辑基本就是这样.其他接口的调用方式也很类似.
1.参数压栈
2.call 函数
3.返回值位于栈顶
4.pop返回值
附加例子
在C中遍历脚本中的table主要是通过lua c api lua_next来完成
具体实践如下:
代码如下:
#include <stdio.h>
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
int table_next(lua_State *L, int i,char **k, char **v)
{
if ( lua_next(L, i) !=0 )
{
*k = (char *)lua_tostring(L, -2);
*v = (char *)lua_tostring(L, -1);
lua_pop(L, 1);
return 1;
}
else
return 0;
}
int main(void)
{
lua_State *L;
int t_idx;
char *k= NULL;
char *v= NULL;
L = lua_open();
luaL_openlibs(L);
luaL_loadfile(L, "luatest.lua");
lua_pcall(L,0,0,0);
lua_getglobal(L,"testtab");
t_idx = lua_gettop(L);
lua_pushnil(L);
while( table_next(L,1,&k,&v) != 0)
{
fprintf(stderr, "k[%s]-v[%s]\n",k,v);
}
lua_close(L);
return 1;
}
脚本代码为:
[opensource@localhost ppt]$ cat luatest.lua
testtab={
MsgCode = "1",
Host = "127.0.0.1",
abc = "test",
id=100,
}
print("ok")
具体实践如下:
代码如下:
#include <stdio.h>
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
int table_next(lua_State *L, int i,char **k, char **v)
{
}
int main(void)
{
}
脚本代码为:
[opensource@localhost ppt]$ cat luatest.lua
testtab={
MsgCode = "1",
Host = "127.0.0.1",
abc = "test",
id=100,
}
print("ok")