3

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 :)

Stefan Dimeski
  • 438
  • 4
  • 16
  • try `Person pers = *lref_p.cast();` – ryanpattison Aug 27 '15 at 16:20
  • Nope, still not working! @rpattiso – Stefan Dimeski Aug 27 '15 at 18:12
  • 1
    An [MCVE](http://stackoverflow.com/help/mcve) and description of how it terminates (with what error message) would be great. – ryanpattison Aug 27 '15 at 20:21
  • @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(l, 1, false);` – Stefan Dimeski Aug 28 '15 at 12:44
  • Great, that looks cleaner too. You can post your solution as an answer. – ryanpattison Aug 28 '15 at 12:47
  • @rpattiso Do you have any idea though, why as the second argument here `get(l, 1, false)` I had to use 1 instead of -1 as that parameter should be the index on the stack. The function has `assert(index > 0)` I have no idea why. – Stefan Dimeski Aug 28 '15 at 13:04

1 Answers1

2

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);

Stefan Dimeski
  • 438
  • 4
  • 16