P
P
Pavel2014-04-13 13:43:12
C++ / C#
Pavel, 2014-04-13 13:43:12

Binding Lua to C++ Objects

How is the problem of binding specific C++ methods to Lua functions solved when embedding Lua in C++?
I found many examples, but they all use deprecated constructs like luaL_register and luaL_openlib.
For now, I use the following solution: store a pointer to the original object as userdata, and then pass this pointer as a parameter when calling the function.
But with this approach, the Lua code becomes somewhat .. inconvenient.
Lua

body.setRotation(body.ptr, body.getRotation(body.ptr) + 0.1)
C++
int cmdGetRotation(lua_State* L)
{
  IActor* actor = (IActor*)lua_touserdata(L, 1);
  lua_pushnumber(L, actor->getRotation().getValue());
  return 1;
}

int cmdSetRotation(lua_State* L)
{
  IActor* actor = (IActor*) lua_touserdata(L, 1);
  actor->setRotation(lua_tonumber(L, 2));
  return 0;
}

How can the situation be improved?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
NeonMercury, 2014-04-15
@aspiring

Have you thought about luabind?
Yes, it's a bit non-trivial to understand and compile, but it's worth it. Then throwing classes and objects into lua is a real pleasure. Here is a sample code:
https://github.com/NeonMercury/time-killer/blob/ma...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question