local part = Instance.new("Part",workspace) local function WrapThisPart(block) local properties = {} local metamethod = {} properties.Speed = 20 properties.Height = 2 metamethod.__index = block function metamethod.__newindex(self,index,value) properties[index] = value end return setmetatable(properties,metamethod) end local itemWithWrapper = WrapThisPart(part) print(itemWithWrapper.Speed) -- returns 20 print(itemWithWrapper.Weight) -- error
Hi everyone,
Im having trouble trying to call the meta methods on the code above. I can call the values that are already defined in properties, however, the metamethod is not executed when i call a variable that is not defined.
I also dont know how to call the new index function. How would i be able to do that?
Thanks
You can call the new index function if, well, just assign it a value. But make sure you use rawset
and rawget
instead of table[index]=value
and table[index]
which causes a C Stack Overflow.
Also note: the difference of metamethod __index
and __newindex
is whether you want to assign a new value or not.
My example:
local a=setmetatable({},{ __newindex=function(self,i,v) rawset(self,i,v); end; __index=function(self,i) return rawget(self,i) end; }); print(a.Wow) --> Metamethod __index activates here, since we have not assigned an index for table a, it returns nil. Notice how I did not use an = a.Wow=10-- Metamethod __newindex activates here. Notice how I used an =. print(a.Wow)--> Metamethod __index activates here once more but this time, since we used rawset to assign the table, it now returns 10