lua-users home
lua-l archive

Re: protecting exported data from within C

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


However, I find I can still modify the value of Account.version. I only get the error message
if I try and add new fields to the table. From the description in the
book my function should
be called whenever lua tries to assign something to the table.
No. The __newindex metamethod will be called if, and only if, there are no corresponding value in the respective table. To avoid such behavior, you could create a table for the __index metamethod which will hold read-only values, and create a function for the __newindex metamethod that will check if the value already exists in the __index table.
The __newindex function would be something like:
__newindex = function (obj,key,value)
	local meta = getmetatable(obj)
	if type(meta)~='table' or type(meta.__index)~='table' then
		return
	end
	if rawget(meta.__index,key)~=nil then
		error('Attempt to override "'..tostring(key).. '" - a constant value')
	else
		rawset(obj,key,value) -- Adds it to the table.
	end
end
--rb

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