轉自: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)
{
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")