Game Development Reference
In-Depth Information
Every time the table is accessed, the __index metafunction is invoked.
Note
So, you have to be careful when accessing a table value from inside of the __index function. It can
lead to a circular loop, causing a stack overflow, as shown in the definition following:
__index = function(tbl, key)
local a = tbl[key]
if a <=0 then a = 0 end
if a > 5 then a = 0 end
return a
a = tbl[key] , will actually trigger another __index function call, and that in turn will invoke
rawget , which retrieves the value of the table without invoking the __index metamethod. So,
local a = rawget(tbl, key)
if a<=0 then a = 0 end
if a > 5 then a = 0 end
return a
end
__newindex
This function is similar to the __index function, but is different in the way it's used to set a value; so,
when we assign a value to a table, this function is called. This gets passed three parameters: the
table, the key, and the value.
a = setmetatable({},{
__newindex = function(t, key, value)
print("Setting [" .. key .. "]=" .. value)
rawset(t, key, value )
end})
a.year = 2012
a.apps = 15
In a way similar to the preceding example where table[key]=value would invoke the __newindex
function and could get into an endless loop and cause errors, this example uses rawset to set the
value of the key.
 
Search WWH ::




Custom Search