[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Getting values in C++ from a Lua table
- From: Florian Berger <fberger@...>
- Date: Tue, 20 Apr 2004 16:25:18 +0300
Jose Marin wrote:
The problem is how to get tha values of the table from
a C++ program...
Hi.
I made following example (see below). I hope it helps.
Regards
Floru
run.lua:
level1 =
{
music = "music1",
items =
{
A = 1,
B = 2,
{
c = "C",
}
}
}
main.cpp:
#include <stdio.h>
extern "C"
{
#include "lua/lua.h"
#include "lua/lualib.h"
#include "lua/lauxlib.h"
}
// In Lua 5.0 reference manual is a table traversal example at page 29.
void PrintTable(lua_State *L)
{
lua_pushnil(L);
while(lua_next(L, -2) != 0)
{
if(lua_isstring(L, -1))
printf("%s = %s\n", lua_tostring(L, -2), lua_tostring(L, -1));
else if(lua_isnumber(L, -1))
printf("%s = %d\n", lua_tostring(L, -2), lua_tonumber(L, -1));
else if(lua_istable(L, -1))
PrintTable(L);
lua_pop(L, 1);
}
}
void main()
{
lua_State *L = lua_open();
// Load file.
if(luaL_loadfile(L, "run.lua") || lua_pcall(L, 0, 0, 0))
{
printf("Cannot run file\n");
return;
}
// Print table contents.
lua_getglobal(L, "level1");
PrintTable(L);
// Print music field.
lua_getglobal(L, "level1");
lua_pushstring(L, "music");
lua_gettable(L, -2);
if(lua_isstring(L, -1))
printf("\nlevel1.music = %s\n", lua_tostring(L, -1));
lua_close(L);
}
Result:
c = C
A = 1
B = 2
music = music1
level1.music = music1