lua-users home
lua-l archive

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


Emmanuel Oga <emmanueloga@gmail.com> wrote:
>
> IMO there is just too much overhead in using a proxy "just in case the
> user modifies the values".

Yes, I think something simpler is the right approach. For instance, here's
a "class" keyword-alike:

  local class = (function()
    local metaclass = {
      __call =
        function (class, ...)
          local object = {}
	  setmetatable(object,class)
	  if class.init then object:init(...) end
	  return object
        end
    }
    return function (class)
      class = class or {}
      setmetatable(class,metaclass)
      class.__index = class
      return class
    end
  )()

which allows you to just call the class name to construct an instance of
the class. For example,

  local stack = class {
    init = function (self)
      self.n = 0
    end
    push = function (self, item)
      self.n = self.n + 1
      self[self.n] = item
    end
    pop = function (self)
      if self.n < 1 then return nil end
      local item = self[self.n]
      self[self.n] = nil
      self.n = self.n - 1
      return item
    end
  }

  local lifo = stack()
  lifo:push(1)
  lifo:push(2)
  print(lifo:pop()) -- 2

Tony.
-- 
f.anthony.n.finch  <dot@dotat.at>  http://dotat.at/
Rockall, Malin, Hebrides: South 5 to 7, occasionally gale 8 at first in
Rockall and Malin, veering west or northwest 4 or 5, then backing southwest 5
or 6 later. Rough or very rough. Occasional rain. Moderate or good,
occasionally poor.