__update metamethod — intercept writ es to existing keys (patch for 5.5.0)

chen chen <[email protected]>
Newsgroups gmane.comp.lang.lua.general
Message-ID <[email protected]>
Hello,

I've been thinking about the gap between `__newindex` (new keys only) and 
the need to intercept updates to existing keys. The proxy-table workaround 
works but has notable overhead. I put together a small patch (~95 lines) 
for Lua 5.5.0 to explore what a native solution might look like — I'd love 
to hear if this direction has been considered or if there are concerns I'm 
missing.

The patch adds an `__update` metamethod that fires when assigning to an 
existing key (including deletion via nil), complementing `__newindex`. 
Same-value writes are skipped as a fast-path optimization.

```lua
local t = setmetatable({}, {
    __update = function(t, k, v)
        rawset(t, k, v)  -- or do validation, logging, etc.
    end
})
t.x = 1   -- fires (new key, no __newindex)
t.x = 2   -- fires (existing key, different value)
t.x = 2   -- no fire (same value, fast-path skip)
t.x = nil -- fires (existing key, deletion)
```

This eliminates the proxy-table pattern (`__newindex` + `__index` + 
`__pairs` on an empty table). Tables without `__update` have zero overhead 
— a single bit flag gates the fast path.

Full proposal, implementation details, and benchmarks:
https://github.com/Ne9roni/lua-update-metamethod

Feedback welcome!

-- 
You received this message because you are subscribed to the Google Groups "lua-l" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [email protected].
To view this discussion visit https://groups.google.com/d/msgid/lua-l/e5ca8f49-c6d6-42c7-8524-11308ef59914n%40googlegroups.com.
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.