I use the open-source module https://github.com/rxi/classic to write OOP Lua outside of the Playdate SDK. It's a very small (50 loc) module that makes things very easy and readable, and it can do a little bit more than Playdate SDK CoreLibs/object
which I have been missing.
Mixins are one thing I make heavy use of, to allow a more modular and extendable way of doing OOP. See Further Reading below.
What's a Mixin?
In Object-Oriented Programming Mixins can be used for sharing methods between classes, without requiring them to inherit from the same father
rxi/classic approach
Object = require "classic"
PairPrinter = Object:extend()
function PairPrinter:printPairs()
for k, v in pairs(self) do
print(k, v)
end
end
Point = Object:extend()
Point:implement(PairPrinter)
function Point:new(x, y)
self.x = x or 0
self.y = y or 0
end
local p = Point()
p:printPairs()
Output:
x 0
y 0
Mixin.lua
You can add this function to CoreLibs/object, or just to your own file, to add Mixin capability to the Playdate SDK.
-- mixin support
function Object:implements(...)
for _, cls in pairs({...}) do
for k, v in pairs(cls) do
if self[k] == nil and type(v) == "function" then
self[k] = v
end
end
end
end
Note: rxi/classic is under MIT licence, and I make no claim to this code, so if Mixin support was to be officially added to the SDK in some way then that would be great!
CoreLibs/object approach
import "CoreLibs/object"
class('PairPrinter').extends(Object)
function PairPrinter:printPairs()
for k, v in pairs(self) do
if k ~= 'super' then -- this is a bit of a hack
print(k, v)
end
end
end
class('Point').extends(Object)
Point:implements(PairPrinter)
function Point:new(x, y)
self.x = x or 0
self.y = y or 0
end
local p = Point()
p:printPairs()
function playdate:update() end
Output:
x 0
y 0