Call delegation in Lua

delegates, lua

Solution

You can automatically build redirection functions on demand using nested metatable:

----------------------------------
-- 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}            -- main metatable
local mt2 = {__index = build_redirector} -- nested metatable

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() will be invoked with sprite object as self

print(myButton:getDimensions())
-- Sprite.getDimensions() will be invoked with sprite object as self

Problem

I'm working with a game framework on Lua. Now if I want to create a button I do it by creating a table for my button that will hold functions and two sprites (button down and up). Sprites have lot's of basic functions like `setLocation(self, x, y)` or `getDimensions(self)`. I would not want to create lots of functions like this: ``` function button.setLocation(self, x, y) self.buttonUpSprite(self, x, y) end ``` But I'd like to "automatically" delegate most calls made to my button directly to the buttonUp sprite. Just setting the button table's metatable `__index` to point to the sprite would forward the calls the sprite's functions but the `self` reference would point to the button still and not the sprite I'd like to operate on. Is there a clean way of doing this delegation?

Original source