无限制浏览:地址
在C/C++中修改Table和读取Table差别不大。也是非常简单。还是直接上代码:
代码
WriteLuaTable.lua
luat_Test1={a=123, b=456, c=789}
luat_Test2={123, 456, 789}
WriteLuaTable.cpp
#include <lua.hpp>
static void WriteTableFromKey(lua_State *L, const char* lpszTableName, const char* lpszTableItem, int nVal)
{
lua_getglobal(L, lpszTableName);
lua_pushnumber(L, nVal);
lua_setfield(L, -2, lpszTableItem);
lua_pop(L, 1);
}
static void WriteTableFromIndex(lua_State *L, const char* lpszTableName, int index, int nVal)
{
lua_getglobal(L, lpszTableName);
lua_pushnumber(L, nVal);
lua_rawseti(L, -2, index);
lua_pop(L, 1);
}
static void ReadTableFromKey(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);
}
int main (int argc, char* argv[])
{
lua_State *L = lua_open();
luaopen_base(L);
luaL_dofile(L, "WriteLuaTable.lua");
ReadTableFromKey(L, "luat_Test1", "a");
ReadTableFromKey(L, "luat_Test1", "b");
ReadTableFromKey(L, "luat_Test1", "c");
puts("\n");
WriteTableFromKey(L, "luat_Test1", "a", 147); // luat_Test1['a'] = 147
WriteTableFromKey(L, "luat_Test1", "b", 258); // luat_Test1['b'] = 258
WriteTableFromKey(L, "luat_Test1", "c", 369); // luat_Test1['c'] = 369
WriteTableFromKey(L, "luat_Test1", "d", 159); // luat_Test1['d'] = 159
ReadTableFromKey(L, "luat_Test1", "a");
ReadTableFromKey(L, "luat_Test1", "b");
ReadTableFromKey(L, "luat_Test1", "c");
ReadTableFromKey(L, "luat_Test1", "d");
puts("\n--------------------------");
ReadTableFromIndex(L, "luat_Test2", 1);
ReadTableFromIndex(L, "luat_Test2", 2);
ReadTableFromIndex(L, "luat_Test2", 3);
puts("\n");
WriteTableFromIndex(L, "luat_Test2", 1, 147); // luat_Test2[1] = 147
WriteTableFromIndex(L, "luat_Test2", 2, 258); // luat_Test2[2] = 258
WriteTableFromIndex(L, "luat_Test2", 3, 369); // luat_Test2[3] = 369
WriteTableFromIndex(L, "luat_Test2", 4, 159); // luat_Test2[4] = 159
ReadTableFromIndex(L, "luat_Test2", 1);
ReadTableFromIndex(L, "luat_Test2", 2);
ReadTableFromIndex(L, "luat_Test2", 3);
ReadTableFromIndex(L, "luat_Test2", 4);
lua_close(L);
return 0;
}
makefile
CPPFLAG=`pkg-config --cflags lua5.1`
LDFLAG=`pkg-config --libs lua5.1`
CC=g++
all: WriteLuaTable
WriteLuaTable : WriteLuaTable.cpp
$(CC) -o $@ $(CPPFLAG) $(LDFLAG) $<
测试环境
类型 | 值 |
---|---|
操作系统 | Ubuntu 10.10 |
lua | 5.1.4 |