Quirrel4.41.0

types.Class.newmember

Method on every class
class.newmember(key, value, ...): any

Adds a member to the class, optionally as a static one.

The binding carries no declaration string, so the VM cannot report parameter names. The names above are from this page; the types and attributes still come from the VM. The VM also cannot tell an optional parameter from a variadic tail here, so read the brackets and any trailing ... from the prose below, not from the signature.

Parameters

keyanyname of the new slot
valueanyvalue 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

examples/types/class/newmember.nut
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) }
Output:
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 manually

See also

rawsetCreates or replaces a member of the class, and unlike newmember, wires key and value to the roles their names suggest.
lockLocks the class immediately, without creating an instance.
is_frozenReports whether this reference to the class was frozen with freeze().
classclass index