我正在使用 Luabind 将基类从C ++暴露给Lua,我可以从中< a href =“http://www.rasterbar.com/products/luabind/docs.html#deriving-in-lua”rel =“nofollow noreferrer”>在Lua中派生类。这部分工作正常,我可以从Lua中的派生类调用C ++方法。

现在我要做的是在我的C ++程序中获取指向基于Lua的实例的指针。

C ++ - <!> gt;结合

class Enemy {
private:
  std::string name;

public:
  Enemy(const std::string& n) 
    : name(n) { 
  }

  const std::string& getName() const { 
    return name; 
  }

  void setName(const std::string& n) { 
    name = n; 
  }

  virtual void update() { 
    std::cout << "Enemy::update() called.\n"; 
  }
};

class EnemyWrapper : public Enemy, public luabind::wrap_base {
public:
  EnemyWrapper(const std::string& n) 
    : Enemy(n) { 
  }

  virtual void update() { 
    call<void>("update"); 
  }

  static void default_update(Enemy* ptr) {
    ptr->Enemy::update();
  }

};

// Now I bind the class as such:
module(L)
[
class_<Enemy, EnemyWrapper>("Enemy")
  .def(constructor<const std::string&, int>())
    .property("name", &Enemy::getName, &Enemy::setName)
    .def("update", &Enemy::update, &EnemyWrapper::default_update)
];

基于Lua的派生类

class 'Zombie' (Enemy)

function Zombie:__init(name)
    Enemy.__init(self, name)
end

function Zombie:update()
    print('Zombie:update() called.')
end

现在假设我有从Lua创建的以下对象:

a = Zombie('example zombie', 1)

如何在C ++中将该对象的引用作为指向基类的指针?

有帮助吗?

解决方案

如果在Lua中你做了

zombie = Zombie('example zombie', 1)

那么你可以像这样获得僵尸的价值:

object_cast<Enemy*>(globals(L)["zombie"]);

object_castglobals是luabind命名空间的成员,L是你的Lua状态) 这假设您知道在Lua中创建的变量的名称。

你总是可以从Lua调用一个C ++方法来获取指向Enemy的指针:

void AddEnemy(Enemy* enemy) { /* ... */ }
//...
module(L) [ def("AddEnemy", &AddEnemy) ]

并从Lua调用它

a = Zombie("zombie", 1);
AddEnemy(a)

请注意,如果你这样做

AddEnemy(Zombie("temp zombie", 1));

Lua将删除<!> quot; temp zombie <!>在方法调用之后,使对象的任何指针无效。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top