http://blog.csdn.net/cnjet/article/details/5909541
Calling Lua scripts from C + + ' s example is written in post what to embed Lua 5.1 in C + +. Now, let us look at how to access Lua's global variables from C + +.
Value passing between C + + and Lua rely on LUA stack. The Stack is a data structure based on the principle of last in first out (LIFO). This is very important keep on mind while coding with C API of Lua.
p.s:i am using Lua 5.1.3 ' S C API.
12 |
lua_State *L = lua_open(); |
14 |
if(luaL_loadfile(L, "config.lua") || lua_pcall(L, 0, 0, 0)) |
16 |
printf("error: %s", lua_tostring(L, -1)); |
20 |
lua_getglobal(L, "var1"); |
21 |
lua_getglobal(L, "var2"); |
22 |
if(!lua_isnumber(L, -2)) { |
23 |
printf("`var1‘ should be a number/n"); |
26 |
if(!lua_isnumber(L, -1)) |
28 |
printf("`var2 should be a number/n"); |
31 |
var1 = (int)lua_tonumber(L, -2); |
32 |
var2 = (int)lua_tonumber(L, -1); |
33 |
printf("var1: %d/nvar2: %d/n",var1, var2); |
The Lua script "Config.lua":
var1=12var2=34
Compilation line:
g++ -o aconf{,.cpp} -llua -ldl
if (luaL_loadfile(L, "config.lua") || lua_pcall(L, 0, 0, 0))Can be written luaL_dofile(L,"config.lua") as, it does the same thing. By calling lua_getglobal(L, "var1"); , Lua would push the value of var1 to the stack. When execute getglobal for "Var2″, again it would push Var2 's value to the stack, VAR2 would now stack on top of var1.
The most top of the stack would be assign as logical address-1. Stack address-2 'll be at below the stack-1. Therefore to access var1, you have to point to-2. For more info regarding Lua stack, can readhere.
To check the value of type in the Stack-2 (VAR1) was it number, we can use this:
lua_isnumber(L, -2)
To access the value to number, we did this:
lua_tonumber(L, -2)
lua_tonumber(L, -2)as would return as double, therefore we must add (int) in front of the function call. Well, we should the use of this case lua_tointeger(L, -2) .
Again, I can access var1 and var2 one by one, therefore you access both variables from the top stack.
1 |
lua_getglobal(L, "var1"); |
2 |
var1=lua_tointeger(L,-1); |
3 |
lua_getglobal(L, "var2"); |
4 |
var2=lua_tointeger(L,-1); |
When accessing Lua script and trigger exception, the error message would always be push to the stack, so why We can print OU t the message when errors detected like this:
printf("error: %s", lua_tostring(L, -1));
Accessing simple variables are simple, if for accessing table data type, you need more steps, the Lua online ebook does Co ver that.
Accessing Lua global variables from C + +