Skip to content

Instantly share code, notes, and snippets.

@rmxsantiago rmxsantiago/Animal.lua
Last active Aug 13, 2016

Embed
What would you like to do?
Lua Inheritance
Animal = { name="undefined",sound="no sound" }
function Animal:new (newname, newsound)
local o = {name=newname,sound=newsound}
setmetatable(o, self)
self.__index = self
return o
end
function Animal:toString()
animalStr = string.format("%s says %s", self.name, self.sound)
return animalStr
end
require "Animal"
Cat = Animal:new()
function Cat:new (name, sound)
setmetatable( {}, Cat )
self.name = name
self.sound = sound
return self
end
function Cat:toString()
animalStr = string.format("A cat called %s says %s!", self.name, self.sound)
return animalStr
end
require "Animal"
Dog = Animal:new()
function Dog:new (name, sound)
setmetatable( {}, Dog )
self.name = name
self.sound = sound
return self
end
function Dog:toString()
animalStr = string.format("A dog called %s says %s", self.name, self.sound)
return animalStr
end
require "Cat"
require "Dog"
fluffy = Cat:new("Fluffy", "Meow")
print(fluffy:toString())
snoppy = Dog:new("Snoppy", "Woof")
print(snoppy:toString())
animal = Animal:new("Generic Animal", "Noise")
print (animal:toString())
animal = Animal:new()
print (animal:toString())
fluffy = Cat:new()
print(fluffy:toString())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.