lua-users home
lua-l archive

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


just a little inconvenient when used with: 

for k, v in pairs(obj) do … end

the keys in the realobj will be ignored. It's a known issue:

Why don't pairs() and ipairs() obey an __index metamethod
http://lua-users.org/lists/lua-l/2007-09/msg00374.html

/hz


在 2017年1月17日,下午8:46,hz <hz@fiosoftware.com> 写道:

Thanks. 

had implemented as this:
--
setmetatable(obj, {
__newindex = function (tab, k, v)
print('setting: ' .. k .. ' -> ' .. tostring(v))
rawset(tab, k, v)
end
})

which will only trigger the first setting for a new key:
self.data['foo'] = 'bar'
self.data['foo'] = 'next-bar’

any way, nice solution, thanks.


在 2017年1月17日,下午8:06,云风 Cloud Wu <cloudwu@gmail.com> 写道:

hz <hz@fiosoftware.com>于2017年1月18日周三 上午11:45写道:
is there a way to intercept the settable_event?

want to implement kind of getter/setter observer for a table (similar to the KVO in Cocoa). Is there a way to do this in pure lua?


local realobj = {}
local obj = setmetatable({}, { 
  __index = realobj, 
  __newindex = function(self, k, v)
    -- it's settable event for obj
    realobj[k]=v
 end,
})