Skip to content

Instantly share code, notes, and snippets.

@sphuff
Created February 11, 2017 04:00
Show Gist options
  • Save sphuff/ff04f724a2f0a796f6352746c18ea44a to your computer and use it in GitHub Desktop.
Save sphuff/ff04f724a2f0a796f6352746c18ea44a to your computer and use it in GitHub Desktop.
Example of object composition in Lua
-- Generic function declarations
local Barker = {
barks = function(self)
print(self.name .. ' barks')
end
}
local Killer = {
kills = function(self, target)
print(self.name .. ' kills '.. target .. ' with its '.. self.weapon)
end
}
local Eater = {
eats = function(self)
print(self.name .. ' eats')
end
}
local Meower = {
meows = function(self)
print(self.name .. ' meows')
end
}
local Dog = {name = nil}
Dog.__index = Dog -- functions are looked up in Dog's metatable
Dog.eats = Eater.eats
Dog.barks = Barker.barks
-- could have an 'Animal' class that initializes according to species, but
-- that would defeat the purpose of this exercise
function Dog.new(name)
local pupper = {name = name}
setmetatable(pupper, Dog)
return pupper
end
local Cat = {name = nil}
Cat.__index = Cat
Cat.meows = Meower.meows
Cat.eats = Eater.eats
function Cat.new(name)
local kitty = {name = name}
setmetatable(kitty, Cat)
return kitty
end
local Robot = {name = nil, weapon = nil}
Robot.__index = Robot
Robot.kills = Killer.kills
function Robot.new(name, weapon)
local robo = {['name'] = name, ['weapon'] = weapon}
setmetatable(robo, Robot)
return robo
end
local blue = Dog.new('Blue')
blue:eats()
blue:barks()
local roxi = Cat.new('Roxi')
roxi:eats()
roxi:meows()
local ralph = Robot.new('Ralph', 'robo arms')
ralph:kills('a bird')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment