lua-users home
lua-l archive

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



On 31-Aug-05, at 4:42 PM, Romulo Bahiense wrote:

i haven't used metatables so far but the basics are to check, on assignment, wether the index is a string and wether the value is nil (delete index) or
not (new index) and based on that, update a counter in the table

Lua 5.0.2 don't call __newindex when the value is nil (don't ask me why).

In your example, it doesn't call it because the index isn't 'new'

> t = setmetatable({}, {__newindex=function(self,k,v) print(k,v) rawset(self,k,v) end})
> t.a = nil
a       nil
> t.a = nil
a       nil
> t.a = 5
a       5
> t.a = nil
> t.a = 5
a       5
> t.a = 6

__newindex is called if the lookup of the key returns nil (i.e. the key wasn't found.) Setting a key to nil effectively deletes it from the table, so the next set will be "new" again.