[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Prevent table insertions?
- From: Luis Carvalho <carvalho@...>
- Date: Tue, 5 Jun 2007 18:22:12 -0400
> 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>