lua-users home
lua-l archive

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

On 2018-01-29 07:02 AM, Dirk Laurie wrote:
2018-01-29 6:41 GMT+02:00 Italo Maia <>:
2018-01-29 1:40 GMT-03:00 Italo Maia <>:
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]( 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.

    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

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

Ah, OOP you say? Here's the simplest form of OOP:

- No inheritance
- Written in C
- Combine traits from multiple sources (similar to multiple inheritance, but without the drawbacks)
- Compatible with standard Lua

Disclaimer: these emails may be made public at any given time, with or without reason. If you don't agree with this, DO NOT REPLY.