handler 將 Lua 對象及其方法包裝為一個匿名函數。 格式: 函數 = handler(對象, 對象.方法) 在 quick-cocos2d-x 中,許多功能需要傳入一個 Lua 函數做參數,然后在特定事件發生時就會調用傳入的函數。例如觸摸事件、幀事件等等。 local MyScene = class("MyScene", function() return display.newScene("MyScene") end) function MyScene:ctor() self.frameTimeCount = 0 -- 注冊幀事件 self:scheduleUpdate(self.onEnterFrame) end function MyScene:onEnterFrame(dt) self.frameTimeCount = self.frameTimeCount + dt end 上述代碼執行時將出錯,報告“Invalid self”,這就是因為 C++ 無法識別 Lua 對象方法。因此在調用我們傳入的 self.onEnterFrame 方法時沒有提供正確的參數。 要讓上述的代碼正常工作,就需要使用 handler() 進行一下包裝: function MyScene:ctor() self.frameTimeCount = 0 -- 注冊幀事件 self:scheduleUpdate(handler(self, self.onEnterFrame)) end 實際上,除了 C++ 回調 Lua 函數之外,在其他所有需要回調的地方都可以使用 handler()。