Quirrel4.41.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.

Locking does not freeze the class: it only stops new plain fields from being added (newmember/rawset for a fresh key then throws trying to modify a class that has already been instantiated, inherited or is locked manually). New static and function members can still be added afterward - that is how a class gains its instance methods before its very first field default is ever read, without those methods being schedulable as instance-editable state. 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) }

// locking stops new per-instance state; a static member is still allowed
Foo.newmember("shared", 42, true)
println("Foo.shared =", Foo.shared)
Output:
rawset("z", 1) error: trying to modify a class that has already been instantiated, inherited or is locked manually
Foo.shared = 42

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