#objylua module

1 messages · Page 1 of 1 (latest)

willow junco
#

Recreating class objects from Python

Features:

  • Similar to Python
  • Easy to add in project: just copy paste the code
  • Supports class extending

Examples:

-- Creating base class
entity = class()
entity.init = function(self)
    self.pos = { 0, 0, 0 }
    self.rot = { 0, 0, 0 }
    --[[
      Also, you can set properties outside init function:
      entity.init = ...
      entity.pos = {0, 0, 0}
      entity.rot = {0, 0, 0}

      (metatables you need to change in init function)
    ]]--
end
entity.print = function(self)
    print("Entity info:", self.pos, self.rot)
end

-- Extending entity class
animal = class(entity)
animal.init = function(self, sound)
    entity.init(self) -- need to call if function overrided (in python too)
    self._sound = sound
end
animal.sound = function(self)
    print(self._sound)
end

-- Testing
cat = animal("meow")
cat:print() --> entity.print(cat) will be called
cat:sound() --> animal.sound(cat) will be called

Code:

function class_copy(obj, seen) 
if type(obj) ~= "table" then return obj end if seen and seen[obj] then return seen[obj] end local s = seen or {} local res = {} s[obj] = res for k, v in pairs(obj) do res[class_copy(k, s)] = class_copy(v, s) end return res
end

class = function(original)
  local t = {}
  local _mt
  if original == nil then
    _mt = {
      __call = function(self, ...)
        local obj = class_copy(self)
        if obj.init ~= nil then
          obj:init(...)
        end
        return obj
      end,
    }
  else
    _mt = {
      __call = function(self, ...)
        local obj = class_copy(self)

        for key, value in pairs(original) do
          if self[key] == nil then
            obj[key] = value
          end
        end

        if obj.init ~= nil then
          obj:init(...)
        end
        return obj
      end,
    }
  end
  return setmetatable(t, _mt)
end
marble sorrel
#

Cool