lua-users home
lua-l archive

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


2018-01-29 6:41 GMT+02:00 Italo Maia <italo.maia@gmail.com>:
> 2018-01-29 1:40 GMT-03:00 Italo Maia <italo.maia@gmail.com>:
>> Regarding OO with Lua, I hardly miss a built-in "class" support, but the
>> lack of a standard interface for OO Lua libraries is a big bummer. Lots of
>> incompatible OO libs. Something like: "if you want to build a lib to do
>> this, try to make it compatible with this interface/behavior".

> ps: Sorry; [Class-Commons](https://github.com/bartbes/Class-Commons) does just that.

There are also attempts to standardize in several rocks, e.g. Penlight.
Needless to say, they are incompatible with Class-Commons.

Taken together, these make a perfect illustration of why
a standard for Lua OO will never fly. There are so many
ways, and no one is best.

Moreover, it is so easy to roll one's own. The simplest kind takes
maybe 15-20 lines, see below. I just include it in every project
where it is needed and make it global. With something so short
and there to be read, why must I require an external module
and ask the reader to go and read its documentation?

It is based on the notion of a constructor-metatable.

Usage:
   MyClass = class("My Class",methods)  -- optional 'methods': a table
to be inherited
   object = MyClass(...)  -- constructs an empty object, calls
object:init() if it exists.

The code is probably somewhere in PiL, but anyway, here it is.
Works for >=5.1, but  __name is only useful >=5.3. For 5.0, remove
the vararg.

         do  -- encapsulate 'new' as upvalue to 'class'
local new = function(Class,...)  -- generic constructor for all classes
  object = setmetatable({},Class)
  if type(Class.init)=='function' then object:init(...) end
  return object
end

class = function(name,_methods)   -- class creator
  local meta = { __call=new,
    __name="constructor-metatable for class '"..name.."'";
    __index = _methods
    }
  local methods = {__name = name}
  methods.__index = methods
  return setmetatable(methods,meta)
end
         end -- of class mechanism