How am i supposed to bind int& f(void) using luabind?

162 views Asked by At

I'm new to luabind and i'm struggling finding an answer to a question that is probably silly.

Let's say i've got this:

int x = 0;

int& f(void)
{
    return x;
}

How do i bind f using luabind?

The simple

module(L)
[
    def("f", &f)
];

results in this error when i call f() in a lua script

Error: std::runtime_error: 'Trying to use unregistered class'

I guess there must be a way to tell luabind to wrap the reference with some registered class but i couldn't find anything working

1

There are 1 answers

0
Oliver On

Things are different in Lua:

x = 123
function f() return x end
a = f()
x = 456
print(a) -- prints 123

What this means is that you can't directly wrap C++ f() for use in Lua; you have to ask yourself what is the meaning of this operation, how will you use this operation on Lua side, and then create the equivalent in Lua. If modifying the C++ level is possible, you will have a different solution than if it is not.

Example: f returns a reference to a global, presumably so that the global can be modified later (if it returned const int& it would be a different problem). How would you do this in Lua? You could put the globals that can be referenced inside a table and return the index into the table:

g = {x = 123}
function f() return 'x' end
at = f()
print(at.x) -- prints 123
g.x = 456
print(at.x) -- prints 456

Another possibility is to create a table and set its metatable such that doing a.x fetches the 'x' in _G instead of a. There are other ways; it really depends on your requirements.