[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Immutable tables
- From: Mark Hamburg <mark@...>
- Date: Fri, 9 Mar 2012 07:38:59 -0800
On Mar 9, 2012, at 3:14 AM, Dirk Laurie wrote:
>>
>> Immutable tables and immutable variables would be a valuable
>> addition.
>
> Let's think about implementation.
>
> Immutable tables, easy. Put something in the metatable to mark it.
>
> Immutable variables, not so easy. Variables are just entries in _ENV,
> and their names are just the keys. _ENV can be any table. You need
> to keep the information "in this table, assignment to or deletion of
> this key is not allowed". `Node` has no spare bits.
>
> So, we may as well implement immutable tables and variables at
> the Lua level. A field `__immutable` in the metatable will serve
> nicely. If it is a table, it contains a list of immutable names.
> If it tests `false` nothing about it is immutable. If it is `true`,
> the whole table is immutable.
>
> Of course, any table exploiting `__immutable` will have to be
> a proxy table so you can catch __newindex.
>
> Everything can go into a module. The user will see:
>
> ----
> immutable = require "immutable"
>
> reserved_names = immutable(_ENV,{})
> reserved_names.x = true -- x is now immutable
> ----
>
> I'll sit down and write the code next time I feel I really need these
> immutable thingies. Which probably means never.
I would think the whole point would be to avoid the need for a proxy table and all of the extra thought that tends to require to get the details right.
This could also be handled with a __write metamethod that works like __newindex but catches all writes. It could have the special behavior that __write = false meant immutable though optimizing what's essentially an error case is probably not worth it.
Should rawset be able to get around immutability? Probably though it definitely becomes a "use at your own risk" sort of thing then. The table functions, however, absolutely should check it which is a problem since they use rawseti right now. They could, however, check it at the beginning of the operation and then use rawseti for the rest of the work.
I suspect — with no actual evidence — that tables writes are rare enough that checking for a fast metamethod on write would not be a huge performance burden. But it is worth bearing in mind that this would hit every table write and not just those to immutable tables would be affected by this extension. Any performance payoff would come in less use of proxy tables.
Mark