C ++에서 LUA 객체 인스턴스에 대한 포인터 획득
문제
나는 사용 중입니다 Luabind C ++에서 LUA로 기본 클래스를 노출하려면 LUA에서 수업을 도출하십시오. 이 부분은 올바르게 작동하며 LUA의 파생 클래스에서 C ++ 메소드를 호출 할 수 있습니다.
이제 내가하고 싶은 것은 C ++ 프로그램의 LUA 기반 인스턴스에 대한 포인터를 얻는 것입니다.
C ++ -> 바인딩
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 ++의 기본 클래스에 대한 포인터로 해당 객체를 참조하는 방법은 무엇입니까?
해결책
루아에 있다면 당신은 그렇게합니다
zombie = Zombie('example zombie', 1)
그런 다음 다음과 같이 좀비의 가치를 얻을 수 있습니다.
object_cast<Enemy*>(globals(L)["zombie"]);
(object_cast
그리고 globals
Luabind 네임 스페이스의 구성원입니다. L
Lua State)) 이것은 Lua에서 만든 변수의 이름을 알고 있다고 가정합니다.
Lua의 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"를 삭제하고 객체에 대한 포인터를 무효화합니다.
제휴하지 않습니다 StackOverflow