types.Class.newmember
classAdds a member to the class, optionally as a static one.
... from the prose below, not from the signature.Parameters
key | any | name of the new slot |
value | any | value stored in it |
... | any | repeats |
Return value
The class, so calls can be chained.
Errors
Throws wrong number of parameters passed to native closure 'newmember' (N passed, at least 3 required) when value is missing; both key and value are required.
On a class locked by lock, or one already instantiated or inherited from, adding a non-static member throws trying to modify a class that has already been instantiated, inherited or is locked manually. On a frozen reference it throws trying to modify immutable 'class'.
Notes
A third, boolean argument requests a static member: one value shared by every instance rather than a per-instance default. The VM cannot report that parameter, because this method is bound with a type mask, so it is absorbed into the trailing ... of the signature above.
A locked class still accepts a static member. Locking stops new per-instance state, not new shared state, so newmember(key, value, true) succeeds where newmember(key, value) throws.
Quirrel classes have no per-member attribute storage, so there is no attributes argument, whatever older Squirrel-family references show.
Example
class Foo {}
println("Foo.newmember(\"k\", \"v\") == Foo =", Foo.newmember("k", "v") == Foo) // returns the class, so calls chain
println("Foo.k =", Foo.k)
// a third argument makes the member static: one value shared by all instances
class Bar {}
Bar.newmember("shared", 42, true)
println("Bar().shared =", Bar().shared)
// locking stops new per-instance state, but not new shared state
class Locked { x = 1 }
Locked.lock()
Locked.newmember("also_shared", 7, true)
println("Locked.also_shared =", Locked.also_shared)
try { Locked.newmember("nope", 1) } catch (e) { println("newmember(\"nope\", 1) error:", e) }Foo.newmember("k", "v") == Foo = true
Foo.k = v
Bar().shared = 42
Locked.also_shared = 7
newmember("nope", 1) error: trying to modify a class that has already been instantiated, inherited or is locked manuallySee also
rawset | Creates or replaces a member of the class, and unlike newmember, wires key and value to the roles their names suggest. |
lock | Locks the class immediately, without creating an instance. |
is_frozen | Reports whether this reference to the class was frozen with freeze(). |
| class | class index |