Skip to content

Instantly share code, notes, and snippets.

@josefnpat
Last active June 1, 2017 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josefnpat/ddc0e161093347d14f58a271d3f0e686 to your computer and use it in GitHub Desktop.
Save josefnpat/ddc0e161093347d14f58a271d3f0e686 to your computer and use it in GitHub Desktop.
Lua 5.1 OOP Inheritance example
-- @josefnpat's Lua OOP example
-- Example of base class
local vehicleclass = {
-- Example of class variable
_defaultColor = "blue"
}
function vehicleclass.new(init)
init = init or {}
self = {}
-- Example of getter/setter
self.getColor,self.setColor = vehicleclass.getColor,vehicleclass.setColor
-- Example of read only getter
self._wheels = 4
self.getWheels = vehicleclass.getWheels
-- Example of private function
self._isColor = vehicleclass._isColor
-- Example of overloading
self:setColor(init.color or vehicleclass._defaultColor)
return self
end
function vehicleclass:_isColor(color)
return type(color)=="string"
end
function vehicleclass:setColor(color)
assert(self:_isColor(color),"invalid color `"..tostring(color).."`")
self._color = color
end
function vehicleclass:getColor()
return self._color
end
function vehicleclass:getWheels()
return self._wheels
end
--return vehicleclass -- end of module
-- Example of inherited class
local motorcycleclass = {}
function motorcycleclass.new(init)
init = init or {}
-- Example of inheriting the vehicle class
self = vehicleclass.new(init)
-- Example of overloading a private variable
self._wheels = 2
-- Example of extending vehicle
self._helmet = init.helmet or true
self.getHelmet,self.setHelmet = motorcycleclass.getHelmet,motorcycleclass.setHelmet
-- Example of extending the overload
self:setColor(init.color or "red")
return self
end
function motorcycleclass:getHelmet()
return self._helmet
end
function motorcycleclass:setHelmet(helmet)
assert(type(helmet)=="boolean")
self._helmet = helmet
end
--return motorcycleclass -- end of module
-- Usage example
-- Inclusion of modules:
--vehicleclass = require"vehicleclass"
--motorcycleclass = require"motorcycleclass"
harley = motorcycleclass.new{color="green"}
print("The harley is `"..harley:getColor().."` and has "..harley:getWheels().." wheels")
harley:setColor("red")
print("The harley is now `"..harley:getColor().."` and has "..harley:getWheels().." wheels")
print("The harley "..(harley:getHelmet() and "has" or "does not have").." a helmet")
harley:setHelmet(false)
print("Now, the harley "..(harley:getHelmet() and "has" or "does not have").." a helmet")
bmw = vehicleclass.new{color="blue"}
print("The bmw is `"..bmw:getColor().."` and has "..bmw:getWheels().." wheels")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment