lua-users home
lua-l archive

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

Lucas Ackerman escribió:

> ...I was just observing that
> locals-as-tables (or something similar) is the one piece missing in
> Lua's nearly-complete meta-power in the "what is an object" sense.
> Global access through tables, tables with function call semantics,
> functions with global tables setting, but no "object" that's a true
> function/table hybrid.  I merely find it an interesting idea.

Me too, but I don't think that Lua is missing that feature. See my little
treatise on FuncTables, which I will expand on at some point, maybe. A
table with functional call semantics is exactly a function/table hybrid.

Consider the following, slightly simplified but could be expanded with ...

function Hybrid(fn)
  return setmetatable(
           {__function = fn},
           {__call = function(t, arg) return t[__function](t, arg) end })

myfunction = Hybrid(
  function(self, x)
    -- the function itself is self.__function
    self.__function(x - 1)
    -- I've got persistent state variables
    self.times_called = self.times_called + 1
    -- I can even change what the function will do next time
    self.__function = do_something_else

-- I can get at the persistent state variables from here, too
myfunction.times_called = 0

-- etc.