lua-users home
lua-l archive

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


Hi,

sorry for this question, may be it's so trivial... but I got
stuck... I just try to understand what's the difference between
two methods below, where I'ld like to make a read only table.

x = {a = "AA"}

function readonlytable(table)
    return setmetatable({}, {
      __index = table,
      __newindex = function(table, key, value)
                    error("Attempt to add a new or modify an exists item to a read-only table")
                   end,
      __metatable = false
    });
end

setmetatable(x, {
    __index    = x,
    __newindex = function(x, key, value)
                    error("Attempt to add a new or modify an exists item to a read-only table")
                end,
    __metatable = false
});

Now I try:

x.a = "BB"

which is *works* (this isn't expected)

x.b = "bbb"

*doesn't work* (this is expected)

When I do:

x = readonlytable(x)

and then

x.a = "BB"

then I got (the expected) behavior:

lua5.3: ro2.lua:8: Attempt to add a new or modify an exists item to a read-only table
stack traceback:
	[C]: in function 'error'
	ro2.lua:8: in metamethod '__newindex'
	ro2.lua:24: in main chunk
	[C]: in ?


So, why does work the function readonlytable() and why doesn't
the "inline" form of same method?



Thanks,


a.