types.Class.lock
Method on every
classLocks the class immediately, without creating an instance.
class Squad { size = 4 }
let locked = Squad.lock()
println("locked == Squad =", locked == Squad)Output:
locked == Squad = trueReturn 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
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 manuallySee also
instance | Creates a new instance of the class without running its constructor. |
newmember | Adds a member to the class, optionally as a static one. |
is_frozen | Reports whether this reference to the class was frozen with freeze(). |
| class | class index |