lua-users home
lua-l archive

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


Never send code you've written late at night to a public mailing list. :)

Correction with a silly but functional example:

do
  local meta = {__call = function(t, ...)
                           return t.__function(t, unpack(arg))
                         end
               }

  function Hybrid(fn)
    return setmetatable({__function = fn}, meta)
  end
end

repeater = Hybrid(
  function(self, n, str)
    -- I've got persistent state variables
    self.times_called = (self.times_called or 0) + 1
    -- I can get at the base function and even change it
    -- so it will do something different next time
    if self.times_called >= 99 then
      self.__function =
        function() return "Sorry, I'm tired of repeating myself" end
    end
    -- I can use the table for configuration, and
    -- the functable itself is self, so I can recurse
    if n == 0 then return ""
      elseif n == 1 then return str
      else return str .. (self.delim or ", ") .. self(n - 1, str)
    end
  end)

--- sample run ---

> -- I can get at the state variables from here, too
> repeater.delim = "; "
> print(repeater(7, "hello"))
hello; hello; hello; hello; hello; hello; hello
> print(repeater.times_called)
7
> _ = repeater(90, "hello")
> print(repeater.times_called)
97
> print(repeater(7, "hello"))
hello; hello; Sorry, I'm tired of repeating myself