lua-users home
lua-l archive

Re: Prevent table insertions?

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


> I'm looking to find a way to prevent new values from being entered
> into a table. I tried the read-only table approach from PIL
> (http://www.lua.org/pil/13.4.5.html) which works as advertised.
> However, I can still insert values like:
> 
> table.insert(days, "Frankday")
> 
> Any suggestions?
You can use a userdata proxy:
function readonly(t)
 local u = newproxy(true)
 local mt = getmetatable(u)
 mt.__index = t
 mt.__newindex = function()
 error("attempt to update a read-only table", 2)
 end
 mt.__len = function() return #t end
 -- emulate __pairs
 mt.__call = function() return next, t, nil end
 return u
end
Cheers,
Luis.
-- 
A mathematician is a device for turning coffee into theorems.
 -- P. Erdos 
-- 
Luis Carvalho
Applied Math PhD Student - Brown University
PGP Key: E820854A <carvalho@dam.brown.edu>

AltStyle によって変換されたページ (->オリジナル) /