Last active
August 13, 2016 22:44
-
-
Save rmxsantiago/26309b5c58e4cede74faacdc20bc55a3 to your computer and use it in GitHub Desktop.
Lua Inheritance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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