加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 在C中存储对Lua值的引用,如何才能完成?

发布时间:2020-12-16 07:31:58 所属栏目:百科 来源:网络整理
导读:例如,假设我有一个键处理接口,在C中定义为: class KeyBoardHandler { public: virtual onKeyPressed(const KeyEventArgs e); virtual onKeyReleased(const KeyEventArgs e);} 现在,我想将此扩展到Lua,以允许Lua利用并在脚本中注册KeyboardHandler. 到目前为
例如,假设我有一个键处理接口,在C中定义为:

class KeyBoardHandler 
{ 
public:
    virtual onKeyPressed(const KeyEventArgs& e);
    virtual onKeyReleased(const KeyEventArgs& e);
}

现在,我想将此扩展到Lua,以允许Lua利用并在脚本中注册KeyboardHandler.

到目前为止,这是原型.

class ScriptKeyboardHandler : public KeyboardHandler
{
public:
    ... previous methods omitted
    static void createFromScript(lua_State* L);
    bool createCppData();

private:
    ScriptKeyBoardHandler(lua_State* L);

    int mSelf;
    int mKeyPressFunc;
    int mKeyReleaseFunc;
    lua_State* mpLuaState;
}

现在,我知道实现将是这样的:

ScriptKeyboardHandler::ScriptKeyboardHandler(lua_State* L) :
    mpState(L)
{ }

ScriptKeyboardHandler::onKeyPressed(...) { 
     // check if mKeyPressFunc is a function
     // call it,passing in mself,and the event args as params
} 

// On Key Release omitted because being similar to the key pressed

ScriptKeyboardHandler::createFromScript(lua_State* L)
{
    auto scriptKeyboardHandler = new ScriptKeyboardHandler(L);
    if (scriptKeyboardHandler->createCppData())
    {
        // set the light user data and return a reference to ourself (mSelf)
    }
}

ScriptKeyboardHandler::createCppData() 
{
    // get the constructor data (second param) and find the keyPressed and keyReleased function,store those for later usage
    // any other data within the constructor data will apply to object
}

-- Syntax of the lua code
MyScriptHandler = { }
MyScriptHandler.__index = MyScriptHandler

MyScriptHandler.onKeyPress = function(self,args)
end

handler = createScriptHandler(handler,MyScriptHandler)
registerKeyHandler(handler)

我只是不知道如何在函数作为表中的参数传入时找到这些函数.

我这样做了吗?我希望我是,这是一个痛苦的屁股因为tolua不容易支持虚拟课程,而不是你可以从脚本中得到的.

我不担心其他功能,我怎么从我的C代码中找到这些变量(按键功能等)

解决方法

这大致是我对onKeyPressed的实现.

void ScriptKeyboardHandler::onKeyPressed()
{
   //Get the table corresponding to this object from the C registry
   lua_pushlightuserdata(mpLuaState,this);
   lua_gettable(mpLuaState,LUA_REGISTRYINDEX);

   //Now get the function to call from the object
   lua_pushstring(mpLuaState,"onKeyPress");
   lua_gettable(mpLuaState,-2);

   //Now call the function 
   lua_pushvalue(mpLuaState,-2 ); // Duplicate the self table as first argument
   //TODO: Add the other arguments
   lua_pcall(mpLuaState,1,0 ); // TODO: You'll need some error checking here and change the 1 to represent the number of args.

   lua_pop(mpLuaState,1); //Clean up the stack

}

但是,您还需要更新构造函数以将表示处理程序的lua对象存储到注册表中.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读