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


当然,这是行不通的。如果IState类型的对象,我不知道该说MainState:

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应该有括号吗?有了它们,就会出现没有这样的运算符的错误。

最佳答案

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

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.。我不知道这段代码在您的示例中如何工作。

关于c++ - 从C++基类创建lua对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11485314/

10-08 22:56