lua-users home
lua-l archive

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


On Sat, Aug 13, 2011 at 6:50 PM, Dirk Laurie <dpl@sun.ac.za> wrote:
>    -- see PiL §13.4
>    local proxy = {}
>    local mt = {
>        __index = t,
>        __eq = ctab_eq,
>        __pairs = function() return pairs(t) end,
>        __ipairs = function() return ipairs(t) end,
>        __newindex = function()
>            error("attempt to update a read-only table",2)
>            end
>    }
>    setmetatable(proxy,mt)

__pairs and __ipairs will return the original table allowing for
modification. You need to return a custom iterator. Something like:

function iteratorn (s, var) -- pairs iterator
  assert(not is_mutable(s))
  return next(getmetatable(s).__index, var)
end

function iteratori (s, var) -- ipairs iterator
  assert(not is_mutable(s))
  var = var+1
  local value = rawget(getmetatable(s).__index, var)
  if value == nil then
    return
  else
    return var, value
  end
end

  __pairs = function (t) return iteratorn, t, nil end
  __ipairs = function (t) return iteratori, t, 0 end


-- 
- Patrick Donnelly