

We actually already have support for freezing and use it internally on various builtin tables like math, we just don't expose it to Lua.ī) It allows an easier way to expose immutable objects for consistency/correctness reasons. Reading the table fields or iterating through the table proceeds as usualĪ) It allows an easier way to expose sandboxed objects that aren't possible to monkey-patch for security reasons.Attempts to change the metatable of the table fail.Attempts to add new keys to the table fail, unless _newindex is defined on the metatable (in which case the assignment is routed through _newindex as usual).Attempts to modify the existing keys of the table fail (regardless of how they are performed - via table assignments, rawset, or any other methods like table.sort).When a table is frozen, the following is true: table.isfrozen(t): given a table t, returns a boolean indicating the frozen status fails when t is not a table.eeze(t): given a non-frozen table t, freezes it fails when t is not a table or is already frozen.This proposal proposes formalizing the notion of "read-only" tables by providing two new table functions: However, this results in iteration and length operator not working on the resulting table, and carries a performance cost - both for creating the table, and for repeated property access. To make an existing table read-only, one needs to combine these mechanisms, by creating a new table with a locked metatable, which has an _index function pointing to the old table. With this it's possible to prohibit customizations of a table's behavior, but existing fields can still be assigned to. Today it is also possible to customize the behavior of setmetatable by "locking" the metatable - this can be achieved by setting a meta-index _metatable to something, which would block setmetatable from functioning and force metatable to return the provided value.

Today it is possible to customize the behavior for adding new fields by setting a metatable that overrides _newindex (including setting _newindex to a function that always errors to prohibit additions of new fields). Lua tables by default are freely modifiable in every possible way: you can add new fields, change values for existing fields, or set or unset the metatable. Note: this RFC was adapted from an internal proposal that predates RFC processĪdd eeze which allows to make a table read-only in a shallow way.
