Lua中的调用委派

我正在Lua上使用游戏框架。如果我想创建一个按钮,我会创建一个表格用于存储按钮函数和两个精灵(按下和弹起的按钮)。

精灵有很多基本功能,比如“setLocation(self,x,y)”或“getDimensions(self)”。

我不想创建很多像这样的函数:

function button.setLocation(self, x, y)
   self.buttonUpSprite(self, x, y)
end

但我希望“自动”将大多数调用直接委派给buttonUp精灵。

只需将按钮表的元表“__index”设置为指向精灵,即可将调用转发到精灵的函数,但“self”引用仍将指向按钮而不是我想要操作的精灵。

有没有干净的方法可以进行这种委派?

点赞
用户1847592
用户1847592

你可以使用嵌套元表来自动构建所需的重定向方法:

----------------------------------
-- sprite.lua
----------------------------------
local Sprite = {}

local mt = {__index = Sprite}

function Sprite.new(filename)
   local sprite_object = {
      img = load_image_from_file(filename),
      x = 0,
      y = 0
   }
   return setmetatable(sprite_object, mt)
end

function Sprite:setLocation(x, y)
   self.x = x
   self.y = y
end

function Sprite:getDimensions()
   return self.img.getWidth(), self.img.getHeight()
end

return Sprite

----------------------------------
-- button.lua
----------------------------------
local Sprite = require'sprite'
local Button = {}

local function build_redirector(table, func_name)
   local sprite_func = Sprite[func_name]
   if type(sprite_func) == 'function' then
      Button[func_name] = function(button_object, ...)
         return sprite_func(button_object.up_sprite, ...)
      end
      return Button[func_name]
   end
end

local mt = {__index = Button}            -- 主元表
local mt2 = {__index = build_redirector} -- 嵌套元表

function Button.new(upSprite)
   return setmetatable({up_sprite = upSprite}, mt)
end

return setmetatable(Button, mt2)

----------------------------------
-- example.lua
----------------------------------
local Sprite = require'sprite'
local Button = require'button'

local myUpSprite = Sprite.new('button01up.bmp')
local myButton = Button.new(myUpSprite)

myButton:setLocation(100, 150)
-- Sprite.setLocation() 将以 sprite 对象为自身调用

print(myButton:getDimensions())
-- Sprite.getDimensions() 将以 sprite 对象为自身调用
2013-02-17 11:00:16