lua-users home
lua-l archive

Re: Module (table) protect

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


marcos wurzius wrote:
In lua4 I protect my module(table):
---
my_tag = newtag()
settagmethod(my_tag, 'setglobal', function(table)
error('Alteração não permitida. [ '..table..' ] é um
módulo.') end)
my = {} --my module
settag(my, mylib_tag)
---
So, my=1
generate an error.
How can I do it in lua5?
marcos
It's a bit trickier in lua 5. Here's one possible way:
do
 local G = getfenv()
 local protected = {}
 function protect(name)
 protected[name] = G[name]
 G[name] = nil
 end
	
 local set = function(t, name, value)
 if protected[name] then
 error('Alteração não permitida. [ '..name..' ] é um módulo.')
 else
 rawset(t, name, value)
 end
 end
 setmetatable(G, { __index = protected, __newindex = set})
end
my = {}	--my module
protect 'my'
my = 1	-- error (NOTE: my.foo = 1 does not generate an error)

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