1
votes

I'm designing a GUI system in Lua, bound to C++. I won't go into unnecessary detail here, but essentially the lua script that creates a form looks something like:

local objectTwo = Gui:newObject{
    position = {10,10},
    size = {100,100},
}

local objectOne = Gui:newObject{
    position = {10,10},
    size = {100,100},
    handleOnClick = function(x, y, button)
        objectTwo:setProperties{
            hidden = false
        }
    end
}

Essentially newObject passes the table into C++ and handleOnClick is turned into a custom C++ function class. When that object is clicked, it calls that function class and it's evaluated in Lua.

However, objectTwo no longer exists in Lua, since the script has run, so it tries to call setProperties on nil and crashes.

My question is, how do I ensure that objectTwo can still be referenced in handleOnClick? I would prefer not to put it in a global registry or some such, to avoid polluting the namespace.

Is there something I could do with a closure?

1

1 Answers

0
votes

When the objectOne is being constructed, the local objectTwo variable is not in the scope yet, so Lua assumes reading from global variable objectTwo, which is never defined, so returns nil when read.

At least move the local objectTwo declaration before the code that will reference it. You don't have to define the object right there, assignment can be performed later. But variable declaration must precede the code that wants to access it.

Also pay attention to the ownership over the data/code. You said you 'convert it to custom C++ class' without extra details. You should be aware that you must store the Lua value for the callback function somewhere. Be it registry, or some class-owned table, but still stored somewhere reachable to Lua, so the callback function won't be garbage-collected at some moment later.