Quirrel4.53.0

types.Class.lock

Method on every class
class.lock(): any

Locks the class immediately, without creating an instance.

examples/types/class/lock-basic.nut
class Squad { size = 4 }
let locked = Squad.lock()
println("locked == Squad =", locked == Squad)
Output:
locked == Squad = true

Return value

The class itself.

Errors

Propagates whatever a _lock metamethod throws, if the class defines one.

Notes

A class locks automatically the first time it gains an instance, is used as a base for another class, or has instance() called on it; lock() exists to trigger that permanently-instantiated state on demand, without either. Locking an already-locked class is a harmless no-op.

A locked class is read-only: any change throws trying to modify a class that has already been instantiated, inherited or is locked manually. A _lock metamethod runs before the lock, so it can still add members. If the class has a base, the base is locked first, recursively.

Example

examples/types/class/lock.nut
class Foo { x = 1 }
Foo.lock()

try { Foo.rawset("z", 1) } catch (e) { println("rawset(\"z\", 1) error:", e) }

// a locked class is read-only: a method is rejected too
try { Foo.newmember("helper", @() 42) } catch (e) { println("newmember(\"helper\", ...) error:", e) }
Output:
rawset("z", 1) error: trying to modify a class that has already been instantiated, inherited or is locked manually
newmember("helper", ...) error: trying to modify a class that has already been instantiated, inherited or is locked manually

See also

instanceCreates a new instance of the class without running its constructor.
newmemberAdds a member to the class, optionally as a static one.
is_frozenReports whether this reference to the class was frozen with freeze().
classclass index