3

这很难解释,我在文档或网络上的任何地方都找不到任何内容,所以我认为这将是解决这个问题的合适地方。

我正在尝试使用 C++ 在 Lua 中的对象上注册属性和方法。

这就是我想要在 Lua 中实现的目标:

player = createPlayer()
player:jump() // method
player.x = player.x + 3 // properties

我可以使用 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;
}

但是我如何创建方法和:jump()属性?.setX.getXcreatePlayer

4

1 回答 1

-1

What you could have searched is "Binding C++ to Lua".

Since it's a rather popular question, I'll post an answer with a project compilable online:

Starting from a 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() {}
};

You can then create bindings using LuaBridge without writing the boilerplate for each of the bound members yourself:

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 a dedicated Lua State wrapper LuaState, you can then open a Lua state and perform the bindings:

lua::State state;
luabridge_bind(state.getState());

Running the 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 the whole thing live at Travis-CI

于 2014-08-08T13:41:49.480 回答