-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleOOP.lua
More file actions
48 lines (41 loc) · 1.45 KB
/
SimpleOOP.lua
File metadata and controls
48 lines (41 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
--[[ LuaSOOP - Simple Object Oriented Programming]]
local object = {}
-- Returns a table with .parent field and metatable __index pointing to self.
-- This mean that any key not in the child will be looked up in the parent.
-- Even when keys are overridden, the parent can be accessed through ._parent
-- eg. Fiction = Book:subclass()
function object:subclass ()
local child = {}
setmetatable(child, {__index = self})
child._parent = self
return child
end
-- Essentailly an alias of object:subclass()
-- eg. Dog = class (Animal)
function class (parentClass)
local parent = parentClass or object
return parent:subclass()
end
-- Create a new instance of a class.
-- If passed a table, it calls :init(table) on the new instance,
-- which copies the table to the instance unless :init() has been overridden.
-- eg. ball = Toy:new({bouncy = true, colour = "red", price = 6.5})
function object:new (params)
local instance = object.subclass(self)
if type(params) == "table" then
instance:init(params)
end
return instance
end
-- Essentially an alias of object:new()
-- eg. tree1 = instance (OakTree, {position = {34, 17}, squirrels = true})
function instance (parentClass, params)
local parent = parentClass or object
return parent:new(params)
end
-- Copies a table to the object which calls it.
function object:init (params)
if type (params) == "table" then
for k, v in pairs(params) do self[k] = v end
end
end