Created
September 22, 2012 16:45
-
-
Save bluebanboom/3766708 to your computer and use it in GitHub Desktop.
Example of use lua table in C.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
extern "C" { | |
#include "lua.h" | |
#include "lauxlib.h" | |
#include "lualib.h" | |
} | |
#pragma comment(lib, "liblua.lib") | |
/* | |
-- test.lua | |
test = 2222 | |
keys = {{r = 1}, {r = 2}, {r = 3}, } | |
*/ | |
int main() | |
{ | |
char *luaFile = "test.lua"; | |
// lua初始化 | |
lua_State *L = luaL_newstate(); // new api in lua5.2 | |
luaL_openlibs(L); | |
luaL_loadfile(L, luaFile); | |
if (lua_pcall(L, 0, LUA_MULTRET, 0) != 0) | |
{ | |
printf("error running file %s: %s", luaFile, | |
lua_tostring(L, -1)); | |
} | |
// 读取变量 | |
lua_getglobal(L, "test"); | |
int a = lua_tointeger(L, -1); | |
printf("test = %d\n", lua_tointeger(L, -1)); | |
// 遍历table | |
lua_getglobal(L, "keys"); | |
// 取 table 索引值 | |
int nIndex = lua_gettop(L); | |
// nil 入栈作为初始 key | |
lua_pushnil(L); | |
while (0 != lua_next(L, nIndex)) | |
{ | |
// 处理里层的table | |
// 取key为r的值 | |
lua_pushstring(L, "r"); | |
lua_gettable(L, -2); | |
printf("%d\n", lua_tointeger(L, -1)); | |
// 弹出 value,让 key 留在栈顶 | |
lua_pop( L, 1 ); | |
// 这是第一层talbe | |
lua_pop( L, 1 ); | |
} | |
// 关闭lua | |
lua_close(L); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment