Quirrel4.41.0

freeze

Global, available without an import
freeze(obj): any

Returns a reference to obj with the immutable flag set.

examples/globals/freeze-basic.nut
let loadout = freeze({ ammo = 10 })

println("loadout.ammo =", loadout.ammo)          // reading is normal
try { loadout.ammo = 20 } catch (e) { println("loadout.ammo = 20 throws:", e) }
Output:
loadout.ammo = 10
loadout.ammo = 20 throws: trying to modify immutable 'table'

Parameters

objanyarray, table, instance, class, or userdata

Return value

A reference to the same object obj names, with getobjflags reporting the immutable flag on that reference. obj is not changed itself.

Errors

Throws Cannot freeze <type> for any type other than array, table, instance, class or userdata, for example an int or a function.

Notes

The immutable flag lives on the reference, not on the table or array itself: freeze returns a new reference and leaves the passed-in reference unchanged. Any other existing reference to the same object - a variable it was copied to earlier, or a value already stored in another table - is unaffected and can still write through. Assign the result back over obj when every access should go through the frozen reference (t = freeze(t)).

Content is unaffected by which reference reads it: a write through a still-mutable reference is visible through a frozen one too, since both name the same object. See also is_frozen and its array and instance counterparts, which check this same per-reference flag.

Example

examples/globals/freeze.nut
let t = {a = 1}
let u = t          // alias made before freeze
let f = freeze(t)  // a new, immutable reference to the same table

try { f.b <- 2 } catch (e) { println("f.b <- 2 throws:", e) }
u.a = 2               // still allowed: u itself was never frozen
println("f.a =", f.a)          // visible here too: u and f share the same table

println("getobjflags(t) =", getobjflags(t))  // t's own reference was never marked
println("getobjflags(f) =", getobjflags(f))
Output:
f.b <- 2 throws: trying to modify immutable 'table'
f.a = 2
getobjflags(t) = 0
getobjflags(f) = 1

See also

getobjflagsReturns the engine flag bits stored on obj's reference.
deduplicate_objectWalks obj and merges equal tables and arrays it finds inside.
globalsmodule index