Creating Lua C ++ Properties and Methods
It's quite difficult to explain and I couldn't find anything about it in the documentation or anywhere on the net, so I thought this would be the right place for this question.
I am trying to register properties and methods for an object in Lua using C ++.
This is what I am trying to achieve in Lua:
player = createPlayer()
player:jump() // method
player.x = player.x + 3 // properties
I can easily get the first line in the example using C ++
int create_player(lua_State *L)
{
Player* player = new Player();
..
return 0;
}
int main(int args, char * argv[])
{
lua_State* L = lua_open();
luaL_openlibs(L);
lua_register(L, "createPlayer", create_player);
luaL_dofile(L, "main.lua");
..
return 0;
}
But how do I create a method :jump()
and properties for .setX
and .getX
for createPlayer
?
source to share
What you could find is "Linking C ++ to Lua".
Since this is a fairly popular question, I'll post an answer with a compiled project online:
Starting from the C ++ class:
class Player {
int x;
public:
Player() : x(0) {}
int get_x() const { return x; }
void set_x(int x_) { x = x_; }
void jump() {}
};
Then you can create bindings using LuaBridge without writing a template for each of the related members:
void luabridge_bind(lua_State *L) {
luabridge::getGlobalNamespace(L)
.beginClass<Player>("Player")
.addConstructor<void (*)(), RefCountedPtr<Player> /* shared c++/lua lifetime */ >()
.addProperty("x", &Player::get_x, &Player::set_x)
.addFunction("jump", &Player::jump)
.endClass()
;
}
Using Lua's special state wrapper LuaState , you can open up Lua state and make bindings:
lua::State state;
luabridge_bind(state.getState());
Running your script using some trace output:
try {
static const char *test =
"player = Player() \n"
"player:jump() \n"
"player.x = player.x + 3"
;
state.doString(test);
}
catch (std::exception &e) {
std::cerr << e.what() << std::endl;
}
Produces the following output:
Player
jump
get_x
set_x 3
~Player
You can see all life in Travis-CI
source to share