Lignum

OOHelper

Sep 19th, 2014
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.54 KB | None | 0 0
  1. local function callConstructor(cls, obj, ...)
  2.     for k,v in pairs(cls) do
  3.         if k:lower() == "new" then
  4.             v(obj, ...) -- Call it!
  5.         end
  6.     end
  7. end
  8.  
  9. --[[
  10.     Creates a new class.
  11.     Parameters:
  12.         fTable  - A table containing the class's functions.
  13.         base    - A class to inherit from, if any.
  14. ]]
  15. function newClass(fTable, base)
  16.     local hasBase = (base ~= nil)
  17.  
  18.     fTable.__index = fTable
  19.  
  20.     local meta = {
  21.         __call = function(cls, ...)
  22.             -- This is what allows you to 'call' the class to create an object.
  23.  
  24.             local self = setmetatable({}, cls) -- Create the object.
  25.             callConstructor(cls, self, ...)
  26.             return self
  27.         end
  28.     }
  29.  
  30.     if hasBase then
  31.         -- Inherit...
  32.         meta.__index = base
  33.  
  34.         -- Inject a 'super' object.
  35.         for _,v in pairs(fTable) do
  36.             if type(v) == "function" then
  37.                 local env = getfenv(v)
  38.                 env.super = setmetatable({}, {
  39.                     __index = base,
  40.                     __call = function(cls, ...)
  41.                         -- Instead of instantiating a new object
  42.                         -- from the base class, this will call
  43.                         -- the base class's constructor.
  44.                         callConstructor(base, ...)
  45.                     end
  46.                 })
  47.             end
  48.         end
  49.     end
  50.  
  51.     setmetatable(fTable, meta)
  52.  
  53.     return fTable
  54. end
  55.  
  56. function serialise(obj)
  57.     local tbl = {}
  58.     for k,v in pairs(obj) do
  59.         if type(v) ~= "function" then
  60.             table.insert(tbl, {k, v})
  61.         end
  62.     end
  63.     return textutils.serialise(tbl)
  64. end
  65.  
  66. function unserialise(txt, class)
  67.     local tbl = textutils.unserialise(txt)
  68.     local obj = class()
  69.     for k,v in pairs(tbl) do
  70.         obj[k] = v
  71.     end
  72.     return obj
  73. end
  74.  
  75. serialize = serialise
  76. unserialize = unserialise
Advertisement
Add Comment
Please, Sign In to add comment