Re: __update metamethod — intercept writes to exis ting keys (patch for 5.5.0)
bil til <[email protected]>
| Newsgroups | gmane.comp.lang.lua.general |
|---|---|
| Message-ID | <CAOnDXmG3A0P1bXKDpm=8rNS8SZ2Jg6sPEB6e2hJNLk6iHYHuAw@mail.gmail.com> |
I also like this idea, if I am allowed to comment :). (I am not sure about the solution presented... of course it should be added only if it is not adding too much overhead). (I also recently considered to add a bit handling metaclass in form of "array style" - but finally I decided against array style, as in this case I preferred to create new bit fields with a special "init / open access function", and not allow creating them just by definition of a new array element (in case of such new meta functions - I want to avoid the possibility that a new class is defined by accidential name typing error)). (so if there would be the possibility to use a function like "__update", but NOT support "__newindex", this would solve my objection here). Am Mi., 8. Apr. 2026 um 12:23 Uhr schrieb chen chen <[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. -- 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/CAOnDXmG3A0P1bXKDpm%3D8rNS8SZ2Jg6sPEB6e2hJNLk6iHYHuAw%40mail.gmail.com.