1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| #include<stdio.h>
extern "C" { #include "lua.h" #include "lauxlib.h" #include "lualib.h" } #pragma comment(lib, "lua5.1.lib") void ReadVariable (lua_State *L,int *width,int *height){ lua_getglobal(L,"width"); lua_getglobal(L,"height"); if(!lua_isnumber(L,-2)) luaL_error(L,"`width' should be a number\n"); if(!lua_isnumber(L,-1)) luaL_error(L,"`height' should be a number\n"); *width = (int)lua_tonumber(L,-2); *height = (int)lua_tonumber(L,-1); printf("width is %d ,height is %d\n\n",*width,*height); } static void ReadTableFromItem(lua_State *L, const char* lpszTableName, const char* lpszTableItem) { lua_getglobal(L, lpszTableName); lua_pushstring(L, lpszTableItem); lua_gettable(L, -2); printf("%s.%s=%d\n", lpszTableName, lpszTableItem, (int)lua_tonumber(L, -1)); lua_pop(L, 2); } static void ReadTableFromIndex(lua_State *L, const char* lpszTableName, int index) { lua_getglobal(L, lpszTableName); lua_rawgeti(L, -1, index); printf("%s[%d]=%d\n", lpszTableName, index, (int)lua_tonumber(L, -1)); lua_pop(L, 2); } static void EnumTableItem(lua_State *L, const char* lpszTableName) { lua_getglobal(L, lpszTableName); int it = lua_gettop(L); lua_pushnil(L); printf("Enum %s:", lpszTableName); while(lua_next(L, it)) { printf(" %d", (int)lua_tonumber(L, -1)); lua_pop(L, 1); } printf("\n\n"); lua_pop(L, 1); } int main(int argc, char* argv[]) { if (argc != 2) { printf("param error!\n"); return 0; } char *filename = argv[1]; lua_State *L = lua_open(); luaL_openlibs(L); if(luaL_loadfile(L,filename) || lua_pcall(L,0,0,0)){ luaL_error(L,"loadfile error! %s \n",lua_tostring(L,-1)); } int w=1,h=2; ReadVariable(L,&w,&h); ReadTableFromItem(L, "luat_Test1", "a"); ReadTableFromItem(L, "luat_Test1", "b"); ReadTableFromItem(L, "luat_Test1", "c"); EnumTableItem(L, "luat_Test1"); ReadTableFromIndex(L, "luat_Test2", 1); ReadTableFromIndex(L, "luat_Test2", 2); ReadTableFromIndex(L, "luat_Test2", 3); EnumTableItem(L, "luat_Test2"); getchar(); return 0; }
|