Category talk:Wren-trait: Difference between revisions
Content added Content deleted
(→Source code: Added Const class.) |
(→Source code: Added Var and TypedVar classes.) |
||
Line 128: | Line 128: | ||
static entries { __cmap.toList } |
static entries { __cmap.toList } |
||
} |
} |
||
/* |
|||
Var represents a group of individually named read/write values which are |
|||
stored internally in a map. It can be used to simulate the creation of |
|||
variables at runtime. It can also be used to allow variable names which would |
|||
otherwise be illegal in Wren such as those which include non-ASCII characters. |
|||
*/ |
|||
class Var { |
|||
// Returns the value of 'name' if it is present in the internal map |
|||
// or null otherwise. |
|||
static [name] { (__vmap && __vmap.containsKey(name)) ? __vmap[name] : null } |
|||
// Associates 'value' with 'name' in the internal map. |
|||
// Any existing value is replaced. |
|||
static [name]=(value) { |
|||
if (!__vmap) __vmap = {} |
|||
__vmap[name] = value |
|||
} |
|||
// Removes 'name' and its associated value from the internal map and returns |
|||
// that value. If 'name' was not present in the map, returns null. |
|||
static remove(name) { __vmap.remove(name) } |
|||
// Returns a list of the entries (name/value pairs) in the internal map. |
|||
static entries { __vmap.toList } |
|||
} |
|||
/* TypedVar is similar to Var except that simulated variables always retain the |
|||
same type as they had when they were originally created. |
|||
*/ |
|||
class TypedVar { |
|||
// Returns the value of 'name' if it is present in the internal map |
|||
// or null otherwise. |
|||
static [name] { (__vmap && __vmap.containsKey(name)) ? __vmap[name] : null } |
|||
// Associates 'value' with 'name' in the internal map. |
|||
// Any existing value is replaced. However, it is an error to attempt to replace |
|||
// an existing value with a value of a different type. |
|||
static [name]=(value) { |
|||
if (!__vmap) __vmap = {} |
|||
if (!__vmap.containsKey(name)) { |
|||
__vmap[name] = value |
|||
} else { |
|||
var vtype = value.type |
|||
var mtype = __vmap[name].type |
|||
if (vtype != mtype) { |
|||
Fiber.abort("Expecting an item of type %(mtype), got %(vtype).") |
|||
} else { |
|||
__vmap[name] = value |
|||
} |
|||
} |
|||
} |
|||
// Removes 'name' and its associated value from the internal map and returns |
|||
// that value. If 'name' was not present in the map, returns null. |
|||
static remove(name) { __vmap.remove(name) } |
|||
// Returns a list of the entries (name/value pairs) in the internal map. |
|||
static entries { __vmap.toList } |
|||
}</syntaxhighlight> |
}</syntaxhighlight> |