我正在使用 Luabind从 C++ 向 Lua 公开一个基类,我可以从中 derive classes in Lua .这部分工作正常,我能够从 Lua 中的派生类调用 C++ 方法。
现在我想做的是在我的 C++ 程序中获取一个指向基于 Lua 的实例的指针。
C++ -> 绑定(bind)
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)
then you can get the value of the zombie like this:
object_cast<Enemy*>(globals(L)["zombie"]);
(object_cast
和 globals
是 luabind 命名空间的成员,L
是你的 Lua 状态)
这假设您知道您在 Lua 中创建的变量的名称。
你总是可以从 Lua 中调用一个带有指向 Enemy 指针的 C++ 方法:
void AddEnemy(Enemy* enemy) { /* ... */ }
//...
module(L) [ def("AddEnemy", &AddEnemy) ]
在Lua中调用
a = Zombie("zombie", 1); AddEnemy(a)
请注意,如果您这样做
AddEnemy(Zombie("temp zombie", 1));
Lua 将在方法调用后删除“temp zombie”并使所有指向该对象的指针无效。
关于c++ - 在 C++ 中获取指向 Lua 对象实例的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1441885/