例如,假设我有一个键处理接口,在 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 代码中找到这些变量(按键功能等)