从C++基类创建Lua对象。

我已经将C ++导出为lua的基础类:

class IState
{
    public:
        virtual ~IState() { }
        virtual void Init() = 0;
        virtual void Update(float dSeconds) = 0;
        virtual void Shutdown() = 0;
        virtual string Type() const = 0;
};

//lua的状态基类包装器
struct IStateWrapper : IState, luabind::wrap_base
{
    virtual void Init() { call<void>("Init"); }
    virtual void Update(float dSeconds) { call<void>("Update", dSeconds); }
    virtual void Shutdown() { call<void>("Shutdown"); }
    virtual string Type() const { return call<string>("Type"); }
};

导出代码:

        class_<IState, IStateWrapper>("IState")
            .def("Init", &IState::Init)
            .def("Update", &IState::Update)
            .def("Shutdown", &IState::Shutdown)

接下来:我有一个StateManager和一个函数:void StateManager::Push(IState*)和它的导出:

        class_<StateManager>("StateManager")
            .def("Push", &StateManager::Push)

现在,我想在Lua中创建类型为IState的对象并将其推到StateManager中:

--创建一个表来存储IState cpp类的对象 
MainState = {}

--IState :: Init纯虚拟函数的实现
function MainState:Init()
    print 'This is Init function'
end

function MainState:Update()
    print 'this is update'
end

function MainState:Shutdown()
    print 'This is shutdown'
end

state = StateManager
state.Push(MainState)

当然,这不起作用。我不知道如何说MainState是IState类型的对象:

error: No matching overload found, candidates: void Push(StateManager&,IState*)

UPD

    module(state, "Scene") [
        class_<StateManager>("StateManager")
            .def("Push", &StateManager::Push),

        class_<IState, IStateWrapper>("IState")
            .def("Init", &IState::Init)
            .def("Update", &IState::Update)
            .def("Shutdown", &IState::Shutdown)
    ];

    globals(state)["StateManager"] = Root::Get().GetState(); // GetState() returns pointer to obj

在示例之后:

class 'MainState' (Scene.IState)
function MainState:__init()
    Scene.IState.__init(self, 'MainState')
end
...
state = StateManager
state:Push(MainState())

error: no static '__init' in class 'IState'

是否应该将state = StateManager括起来?这样会有一个错误,表示没有这样的运算符。

点赞
用户734069
用户734069

你不能只是将一个表格扔给 Luabind。如果你想要从一个 Luabind 定义的类派生,你必须遵循 Luabind 的规则。你必须使用 Luabind 的工具来创建一个 Lua 类,并从你的 IState 类中派生。代码如下所示:

class 'MainState' (IState) -- 假设你将 IState 在全局表中注册,而非注册在 Luabind 模块中。

function MainState:__init()
    IState.__init(self, 'MainState')
end

function MainState:Init()
    print 'This is Init function'
end

function MainState:Update()
    print 'this is update'
end

function MainState:Shutdown()
    print 'This is shutdown'
end

state = StateManager()
state:Push(MainState())

此外,请注意最后两行的更改。具体来说,要注意 StateManager 如何被_调用_,而不仅仅是设置到 state 中。同时要注意使用 state: 而不是 state.。我不知道你的示例代码是如何工作的。

2012-07-14 17:43:20