Lua & implicit global state

1.1k views Asked by At

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?

2

There are 2 answers

0
LukeN On BEST ANSWER

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
2
Archinamon On

Any link you use inside the function won't change the var outside of it. You should use smthg like this:

local count
function MyFunc()
      count = 1
end

There is 'local' isn't necessarily.

As alternative I can suggest you to use non-safety method:

count = 0
function MyFunc(v) --we will throw varname as a string inside
     _G[v] = 1 -- _G is a global environment
end
MyFunc('count')
print(count)