lua-users home
lua-l archive

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

Yep, when you call:

tbl[1] = 1

It is calling the __newindex() metamethod. Try this:

> tbl = {}
> setmetatable(tbl, {__newindex = function(t,k,v) print ("test", k, v) end})
> tbl[1] = 1

You'll see how it works.

Now, to track both insertions and overwriting of existing entries in the table, you have to use a proxy table (or something like it). Example:

tbl = {}
tbl.__proxy = {}
mt = {__index = function(t,k) return t.__proxy[k]; end,
__newindex = function(t,k,v) print('tracked', k, v); t.__proxy[k] = v; end}
setmetatable(tbl, mt)

This works by making all values "stored" in tbl not actually stored there, so when there's an access to it (get), it'll invoke the __index metamethod, and retrieve it from __proxy. And when there's a setting of it, since it doesn't exist in tbl, but in tbl.__proxy, it'll go through your __newindex metamethod.

// David Morris-Oliveros
// Camera & Lua Coder

Chris wrote:

   tbl = {}
   setmetatable(tbl, {__index = function(t,k) print("test") end})
   tbl[1] = 1
   tbl[2] = 2

Prints nothing... ?? Also, is there any metamethod that you can hook to know when a value is being set? I know there is __newindex but that only appears to be called for new values being inserted into the table. I want to hook both cases of new values and also setting existing values.

// Chris