lua-users home
lua-l archive

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


I was following through PILv1 online, but it abruptly ended before
discussing how to have both methods like a:size() AND array
indexors like a[2] = 5 or a.some_field = "value" for user data.

Is what I do below a reasonable way to do this? I'll have to rewrite
in C, but I tried pure lua first.

I tried other approaches, for example I thought that perhaps attaching a
metatable to my object's metatable would work, but "self" ends up being
the metatable instead of the object, so that was a dead end.


-- Rewrite in lua of array example from http://www.lua.org/pil/28.4.html
-- that implements both array and OO access.
array = {
  new = function(self, size)
      local o = {
        _size = size,
        _array = {},
      }
      for i = 1, o._size do
        o._array[i] = 0
      end
      setmetatable(o, self)
      return o
    end,

  size = function(self)
      return self._size
    end,

  sum = function(self)
      local accum = 0
      for i = 1, self._size do
        accum = accum + self._array[i]
      end
      return accum
    end,

  __index = function(self, key)
      -- should do bounds checking on array
      return getmetatable(self)[key] or self._array[tonumber(key)]
    end,

  __newindex = function(self, key, value)
      -- should do bounds checking on array
      self._array[tonumber(key)] = value
    end,
}


o = array:new(3)

print(o:size())

print(o:sum())

o[1] = 1
o[2] = 2
o[3] = 3

print(o[2])

print(o:sum())