从c ++基类创建lua对象

时间:2012-07-14 16:12:35

标签: c++ oop lua luabind

我已经从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;
};

// Wraper of state base class for 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:

-- Create a table for storing object of IState cpp class
MainState = {}

-- Implementatio of IState::Init pure virtual function
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())

错误:“IState”类中没有静态“__init”

state = StateManager是否应该括号?有了它们,就会出现错误,没有这样的操作员。

1 个答案:

答案 0 :(得分:2)

你不能只是在Luabind扔桌子。如果您打算从Luabind定义的类派生,则必须遵循Luabind的规则。您必须create a Lua class with Luabind's tools,来自您的IState课程。这看起来像这样:

class 'MainState' (IState) --Assuming that you registered IState in the global table and not a Luabind module.

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.。我不知道这个代码在你的例子中是如何起作用的。