Search code examples
cluaembedded-language

Lua & implicit global state


I'm integrating Lua into my project at the moment, and I'm facing a small design problem on the way. Currently, if I want to get information from my host application into Lua scripts, I call a function that I registered in C, in this fashion:

-- Inside lua
local state = host.get_state()
-- Do something with "state"

Now the problem with that is: the state can obviously change, and the "state" variable will then be outdated and most likely invalid. So far I lived with this because the global state isn't needed too often. It's more problematic in the following scenario:

local user = host.get_user('id')
host.set_user_flags(user, 'abc')
-- internally "user" is now updated, but to get the accurate information in Lua, I
-- will have to explicitly redo "user = host.get_user('id')" for every operation
-- that accesses this table

I have read a bit about references and I think they can help me with this, but I didn't really understand it.

Isn't there some way to just throw around pointers like I can do it in C?


Solution

  • I found out that tables are passed as references and I'm able to modify them from inside the function like this:

    static int dostuff(lua_State *L)
    {
        lua_pushstring(L, "b");
        lua_pushnumber(L, 23);
        lua_settable(L, 1);
    
        return 0;
    }
    /* lua_register(L, "dostuff", &dostuff); */
    

    And inside Lua:

    t = { a = 'a', b = 2 }
    
    print(t.a, t.b)
    dostuff(t)
    print(t.a, t.b)
    

    Will result in:

    a   2
    a   23