On 22/09/15 16:41, Scott Morgan wrote: > > Seeing the following behaviour on various version of Lua: > > Lua 5.2.2 Copyright (C) 1994-2013 Lua.org, PUC-Rio > ~ mt = { __newindex = function(t,k,v) > ~~ print("Setting :", k, "to", v) > ~~ rawset(t,k,v) > ~~ end } > ~ tab = setmetatable({},mt) > ~ return tab > table: 0x671df0 > ~ return tab.test > nil > ~ tab.test = 123 > Setting : test to 123 > ~ tab.test = nil > ~ tab.test = nil > Setting : test to nil > ~ tab.test = nil > Setting : test to nil > ~ tab.test = 321 > Setting : test to 321 > ~ return tab.test > 321 > ~ tab.test = nil > ~ return tab.test > nil > ~ tab.test = nil > Setting : test to nil > > Why isn't the first `tab.test = nil` event being handled by the > metatable? As mentioned, I'm seeing this across Lua versions, 5.1, 5.2 > (as above) and 5.3 (and different OS's/compilers) > > It's weird because, surely, if this is a bug, it has already been seen. > It's such a common pattern. I must be doing something wrong here? > > Scott > Nothing weird or even a bug present here, it is your understanding of __newindex which is incorrect. ""newindex": The indexing assignment table[key] = value. Like the index event, this event happens when table is not a table or when key is not present in table. The metamethod is looked up in table. " At the first call to setting the key's associated value to nil, the key already exists and has an associated value of 123. -- Liam
Attachment:
signature.asc
Description: OpenPGP digital signature