Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local function callConstructor(cls, obj, ...)
- for k,v in pairs(cls) do
- if k:lower() == "new" then
- v(obj, ...) -- Call it!
- end
- end
- end
- --[[
- Creates a new class.
- Parameters:
- fTable - A table containing the class's functions.
- base - A class to inherit from, if any.
- ]]
- function newClass(fTable, base)
- local hasBase = (base ~= nil)
- fTable.__index = fTable
- local meta = {
- __call = function(cls, ...)
- -- This is what allows you to 'call' the class to create an object.
- local self = setmetatable({}, cls) -- Create the object.
- callConstructor(cls, self, ...)
- return self
- end
- }
- if hasBase then
- -- Inherit...
- meta.__index = base
- -- Inject a 'super' object.
- for _,v in pairs(fTable) do
- if type(v) == "function" then
- local env = getfenv(v)
- env.super = setmetatable({}, {
- __index = base,
- __call = function(cls, ...)
- -- Instead of instantiating a new object
- -- from the base class, this will call
- -- the base class's constructor.
- callConstructor(base, ...)
- end
- })
- end
- end
- end
- setmetatable(fTable, meta)
- return fTable
- end
- function serialise(obj)
- local tbl = {}
- for k,v in pairs(obj) do
- if type(v) ~= "function" then
- table.insert(tbl, {k, v})
- end
- end
- return textutils.serialise(tbl)
- end
- function unserialise(txt, class)
- local tbl = textutils.unserialise(txt)
- local obj = class()
- for k,v in pairs(tbl) do
- obj[k] = v
- end
- return obj
- end
- serialize = serialise
- unserialize = unserialise
Advertisement
Add Comment
Please, Sign In to add comment