Friday, March 15, 2013

Accessing Lua global variables from c++


Calling Lua scripts from c++’s example was written in post How 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. Stack is a data structure based on the principle of Last In First Out (LIFO). This is very important keep in mind while coding with C API of Lua.
P.S: I am using Lua 5.1.3’s C API.

01//aconf.cpp
02extern "C" {
03#include "lua.h"
04#include "lualib.h"
05#include "lauxlib.h"
06}
07 
08int main()
09{
10    int var1=0,var2=0;
11 
12    lua_State *L = lua_open();
13    luaL_openlibs(L);
14    if (luaL_loadfile(L, "config.lua") || lua_pcall(L, 0, 0, 0))
15    {
16        printf("error: %s", lua_tostring(L, -1));
17        return -1;
18    }
19 
20    lua_getglobal(L, "var1");
21    lua_getglobal(L, "var2");
22    if (!lua_isnumber(L, -2)) {
23        printf ("`var1' should be a number/n");
24        return -1;
25    }
26    if (!lua_isnumber(L, -1))
27    {
28        printf("`var2 should be a number/n");
29        return -1;
30    }
31    var1 = (int)lua_tonumber(L, -2);
32    var2 = (int)lua_tonumber(L, -1);
33    printf("var1: %d/nvar2: %d/n",var1, var2);
34    lua_close(L);
35 
36    return 0;
37}
The Lua script “config.lua”:
var1=12
var2=34
Compilation line:
g++ -o aconf{,.cpp} -llua -ldl
if (luaL_loadfile(L, "config.lua") || lua_pcall(L, 0, 0, 0)) can be written asluaL_dofile(L,"config.lua"), it does the same thing. By calling lua_getglobal(L, "var1");, Lua will push the value of var1 to the stack. When execute getglobal for “var2″, again it will push var2’s value to the stack, var2 will now stack on top of var1.
The most top of the stack will be assign as logical address -1. Stack address -2 will 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 type in the stack -2 (var1) is it number, we can use this:
lua_isnumber(L, -2)
To access the value to number, we do this:
lua_tonumber(L, -2)
As lua_tonumber(L, -2) will return as double, therefore we must add (int) in front of the function call. Well, we should use lua_tointeger(L, -2) in this case.
Again, I can access var1 and var2 one by one, therefore you access both variables from the top stack.
1lua_getglobal(L, "var1");
2var1=lua_tointeger(L,-1);
3lua_getglobal(L, "var2");
4var2=lua_tointeger(L,-1);
When accessing Lua script and trigger exception, the error message will always push to the stack, that why We can print out the message when errors detected like this:
printf("error: %s", lua_tostring(L, -1));
Accessing simple variables is simple, but for accessing table data type, you need more steps, the Lua online ebook does cover that.

No comments: