3
votes

I have this Lua code:

function returnPerson()
    local person = Person("Mike", 23)     
    return person
end

It returns userdata representing Person(C++ class registered using LuaBridge). So I call this function using lua_pcall and now the last element of the lua stack is that userdata. My question is how do I convert(cast) this userdata at -1 back to Person in C++.

I tried this, but it just terminates the program:

LuaRef lref_p(l);

lref_p.fromStack(l, -1);

Person pers = lref_p.cast<Person>();

I hope it makes sense :)

1
try Person pers = *lref_p.cast<Person *>(); - ryanpattison
Nope, still not working! @rpattiso - user3071028
An MCVE and description of how it terminates (with what error message) would be great. - ryanpattison
@rpattiso After hours of tweaking and trying I found the solution lref_p.fromStack(l, -1); should be replaced with lref_p = LuaRef::fromStack(l, -1) Also I found an easier way of doing this: Person *pers = luabridge::Userdata::get<Person>(l, 1, false); - user3071028
Great, that looks cleaner too. You can post your solution as an answer. - ryanpattison

1 Answers

2
votes

OK, so after hours of tweaking and trying I found the solution. It was the second line: lref_p.fromStack(l, -1); that was the problem. It should be lref_p = LuaRef::fromStack(l, -1);

Also I found an easier and cleaner way of doing this:

Person *pers = luabridge::Userdata::get<Person>(l, 1, false);