lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Op Vr. 22 Feb. 2019 om 11:39 het Eduardo Ochs <eduardoochs@gmail.com> geskryf:

> I just added lots of documentation, including box diagrams and
> a detailed example of use, to the OO mechanism that I've been using
> for years, whose main part is just these these five lines of Lua code:
>
>   Class = {
>       type   = "Class",
>       __call = function (class, o) return setmetatable(o, class) end,
>     }
>   setmetatable(Class, Class)

> I guess that most people here will find it almost offensibly simple

I like it simple! I use a callable metatable too, but cut-and-paste
15 lines.

1, A universal constructor that creates an empty object but
calls your `myclass.init` if you supply one.
2. Method table and metatable are the same.
3. __name in the metatable
4. `is` function
5. Define all methods using non-object syntax.

local new = function(class,...)
  local object = setmetatable({},class)
  if class.init then object:init(...) end
  return object
end

class = function(name)
  local mt = setmetatable({__name=name}, {__call=new})
  mt.__index = mt
  return mt
end

is = function(class,object)
  return getmetatable(object) == class
end