lua-users home
lua-l archive

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


2016-07-22 4:57 GMT+02:00 Patrick Donnelly <batrick@batbytes.com>:
> For some slightly early "It's Friday" discussion, what do you use the
> __call metamethod for? Discuss your favorite hacks, strange problems
> solved, code golf hole-in-ones, etc.
>
> To get discussion started, I'll leave this here:
>
> t = setmetatable({}, {__index = table, __call = function(t, method)
> return function(...) t[method](t, ...) end end}) -- create a method
> binding
> string.gsub("foo", ".", t "insert")
> for k,v in pairs(t) do print(k,v) end --> 1 f \n 2 o \n 3 o \n

I use a minimal object-oriented paradigm in which the method
table is also the __index and the constructor.

local init = function(class,object)
  setmetatable(object,class)
  return object
end

local Class = function(methods,typename)
  methods.__index = methods
  methods.type = function() return typename end
  return setmetatable(methods,{__call = init})
end

I don't package these in a module. They are clearly visible to
whoever reads the listing.

After that, e.g.

Data = Class({},'data')
data = Data{}

I've been using this for so long that I have forgotten where I got it.
Probably from PiL.