lua-users home
lua-l archive

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


On Sun, Aug 14, 2011 at 03:42:21AM +0200, Patrick Donnelly wrote:
> 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:
> 

I also wrote:

> Warning: The safe thing is to make immutable tables only from table
>     constants.  If you have another reference to the table you are
>     making immutable, that reference is not also immutable.

having in mind ordinary use by a possibly absent-minded but not
malicious programmer.  But sure, that advice does not protect against
the sort of hacker who would write

    s = imm {1,2,3}
    _, original = pairs(s)
    original[2] = 'Your PC is stoned'
    print(s[2])     --> Your PC is stoned

I wondered why Roberto's PiL example of a read-only table does not
support pairs/ipairs.  Now I know :-(

Dirk