在 C 中存储对 Lua 值的引用,如何做到这一点
Storing a reference to a Lua value in C, how can it be done?
例如,假设我有一个键处理接口,在C++中定义为:
class KeyBoardHandler
{
public:
virtual onKeyPressed(const KeyEventArgs& e);
virtual onKeyReleased(const KeyEventArgs& e);
}
现在,我想将其扩展到Lua,以允许Lua利用并在脚本中注册键盘处理程序。
这是到目前为止的原型。
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, 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 对象存储到注册表中。
相关文章:
- C++:去引用实际上在做什么
- 我一直得到列表迭代器不可引用,我做错了什么
- 嵌套绑定到成员,需要一个指针,得到了一个引用.做什么
- C 不支持通过引用传递变量.怎么做
- *val 和 &val 在 C++ 中通过引用传递时有何不同
- 我需要做什么才能从 C# 应用程序引用 c++ dll
- 为什么以及在何处在C++中使用引用和指针
- boost::shared_ptr引用计数所做的是求解tr1::shared_pt的原始指针
- 如何做列表的向量引用列表中的值
- c中未定义的引用…我做错了什么?
- 如果一个引用一旦被初始化为一个对象,它就不能被改变,为什么这样做呢?
- Linux c++对main做了未定义的引用
- 未定义的引用静态函数指针成员在c++,我做错了什么
- 对Google Mock返回的引用所做的更改能否反映在原始值中?
- 当你完美转发时,类型名T变成了T&或T&&,但当你不这样做时,T根本不是引用。如何?
- C++ - 引用和运算符=在这里做什么
- 编译器会根据我处理未引用参数的方式做不同的事情吗
- c++:独立引用是用来做什么的
- C++11编译器何时会使RVO和NRVO优于移动语义和常量引用绑定
- 如何创建对数组和boost::array的引用(或不必这样做的想法)