Re: __update metamethod — intercept wr ites to existing keys (patch for 5.5.0)
Rett Berg <[email protected]>
| Newsgroups | gmane.comp.lang.lua.general |
|---|---|
| Message-ID | <[email protected]> |
> __index and ___newindex are called only for not-found key.
Why this non-existence criteria? Why not throw them away in 2026 and
add read and write wrappers for table slots? Like OnRead(), OnWrite()
(or __read, __write if you like underscores)?
I *believe* the reason is performance. __update would require the write
path to _always_ check for the metamethod even if the item was there,
whereas __newindex only requires checking it in the nil case, which is more
rare for common well-formed tables.
So in the current common case the write path looks like this:
find slot
if(slot filled) put in slot
else {
find newindex
if(has newindex) __newindex(self, k, v)
else put in slot
}
Update would require the "find update" to be moved up, which would reduce
performance for the common case I mentioned.
However, I've been wondering lately whether metatables (do? could?) have
some kind of performance enhancement where metamethods are actually stored
in a side-struct, avoiding a hash table lookup... or similar. This would
still have a performance cost for update, but it would be less.
Just some thoughts,
- Rett
On Thursday, April 9, 2026 at 4:52:49 AM UTC-6 Yan wrote:
> It seems that in Lua 5.5, the `isrealasize` is no longer in use, and the
> corresponding comments should be able to be removed.
>
> ```
> src/ltable.c:** dummy bit must be exchanged: The 'isrealasize' is not
> related
> src/ltm.h:** the table is using the dummy node; bit 7 is used for
> 'isrealasize'.)
> ```
>
>
> 在2026年4月8日星期三 UTC+8 18:23:46<chen chen> 写道:
>
> 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.
>
>
--
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/2868bb9c-9a82-4848-940a-04d79036f57bn%40googlegroups.com.