首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在C中存储对Lua值的引用,该怎么做呢?

在C中存储对Lua值的引用,该怎么做呢?
EN

Stack Overflow用户
提问于 2012-08-19 11:14:55
回答 1查看 248关注 0票数 4

例如,假设我有一个键处理接口,在C++中定义为:

代码语言:javascript
运行
复制
class KeyBoardHandler 
{ 
public:
    virtual onKeyPressed(const KeyEventArgs& e);
    virtual onKeyReleased(const KeyEventArgs& e);
}

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

这是到目前为止的原型。

代码语言:javascript
运行
复制
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;
}

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

代码语言:javascript
运行
复制
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代码中找到这些变量(按键函数等

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-08-19 11:36:59

下面是我的onKeyPressed实现的大致情况。

代码语言:javascript
运行
复制
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, 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对象存储到注册表中。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12023943

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档