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.

extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"

int main()
    int var1=0,var2=0;

    lua_State *L = lua_open();
    if (luaL_loadfile(L, "config.lua") || lua_pcall(L, 0, 0, 0))
        printf("error: %s", lua_tostring(L, -1));
        return -1;

    lua_getglobal(L, "var1");
    lua_getglobal(L, "var2");
    if (!lua_isnumber(L, -2)) {
        printf ("`var1' should be a number\n");
        return -1;
    if (!lua_isnumber(L, -1))
        printf("`var2 should be a number\n");
        return -1;
    var1 = (int)lua_tonumber(L, -2);
    var2 = (int)lua_tonumber(L, -1);
    printf("var1: %d\nvar2: %d\n",var1, var2);

    return 0;

The Lua script “config.lua”:


Compilation line:

g++ -o aconf{,.cpp} -llua -ldl

if (luaL_loadfile(L, "config.lua") || lua_pcall(L, 0, 0, 0)) can be written as luaL_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 read HERE.

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.

lua_getglobal(L, "var1");
lua_getglobal(L, "var2");

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.

Lua Online Ebook: Programming in Lua

2 thoughts on “Accessing Lua global variables from c++

  1. You forgot to put int in front of width and height. Also you want to print width and height not var1 and var2 for this snippet to make sense in using lua. But other than that, this is pretty good.

Leave a Reply

Your email address will not be published. Required fields are marked *