Created
February 6, 2020 13:22
-
-
Save tonetheman/dbb7b5b7b3488d02faa4d554e6a9bf40 to your computer and use it in GitHub Desktop.
classic example for lua OO
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
--[[ | |
example of using | |
https://github.com/rxi/classic | |
]] | |
local Object = require("classic") | |
local Actor = Object:extend() -- new class | |
function Actor:new(id) -- ctor | |
-- syntax little wonky to me here | |
-- yourself.super gets to the parent | |
-- class, then call with dot and pass self | |
Actor.super.new(self) | |
-- specific to this class | |
self.id = id | |
end | |
function Actor:repr() | |
return tostring(self.id) | |
end | |
local Player = Actor:extend() | |
function Player:new(name,id) | |
-- Player.super is parent class | |
-- new pass self and args | |
Player.super.new(self,id) | |
-- specific to this class | |
self.name = name | |
end | |
function Player:repr() | |
-- Player.super parent class | |
-- call with dot | |
local ts = Player.super.repr(self) | |
ts = ts .. " " .. self.name | |
return ts | |
end | |
-- instance of Actor | |
local a = Actor(10) | |
print(a:repr()) | |
-- instance of Player | |
local p = Player("tony",20) | |
print(p:repr()) | |
-- late mixin | |
local PairPrinterMixin = Object:extend() | |
function PairPrinterMixin:printPairs() | |
for k,v in pairs(self) do | |
print(k,v) | |
end | |
end | |
Player:implement(PairPrinterMixin) | |
p:printPairs() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment