lua-users home
lua-l archive

[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

	if rawget(meta.__index,key)~=nil then
		error('Attempt to override "'..tostring(key).. '" - a constant value')
		rawset(obj,key,value) -- Adds it to the table.