Stefan Dimeski
Stefan Dimeski

Reputation: 458

How to convert Lua userdata to C++ class object?

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

Upvotes: 3

Views: 839

Answers (1)

Stefan Dimeski
Stefan Dimeski

Reputation: 458

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

Upvotes: 2

Related Questions