Category talk:Wren-dynamic: Difference between revisions

m
Now uses Wren S/H lexer.
m (Fixed syntax highlighting.)
m (Now uses Wren S/H lexer.)
 
(2 intermediate revisions by the same user not shown)
Line 1:
===Generation of classes at runtime===
 
There is often a need in Wren programming for simple classes which would be represented in some other languages by enums, 'flags' enums, constant groups, tuples, structs or unions. None of these are supported directly by Wren and, although they can be easily simulated, they are rather tedious to write.
 
This module aims to rectify this by providing templates to generate such classes at runtime for simple cases. In particular:
Line 7:
* Enum values always start from an initial integer value (often 0) and are incremented by 1 which is the commonest case.
* 'Flags' enums are always powers of 2, starting from 1 (= 2^0).
* Groups represent other groupings of related named constants of any type.
* Structs and tuples both represent data classes but fields for the former are read/write and for the latter read only.
* Union represents a value which can be any one of a set of types. A single storage location stores the value or a reference thereto.
Line 13 ⟶ 14:
To create for example a Point tuple, one could proceed as follows:
 
<syntaxhighlight lang=ecmascript"wren">import "/dynamic" for Tuple
 
var Point = Tuple.create("Point", ["x", "y"])
Line 22 ⟶ 23:
 
===Source code===
<syntaxhighlight lang=ecmascript"wren">/* Module "dynamic.wren" */
 
import "meta" for Meta
Line 135 ⟶ 136:
// Convenience version of above method which does not have a member with a value of zero.
static create(name, members) { create(name, members, false) }
}
 
/* Group creates a group of related named constants of any type.
The group has:
1. static property getters for each member,
2. a static 'members' property which returns a list of its members as strings, and
3. a static 'values' property which returns a list of their corresponding values.
*/
class Group {
// Creates a class for the Group (with an underscore after the name) and
// returns a reference to it.
static create(name, members, values) {
if (name.type != String || name == "") Fiber.abort("Name must be a non-empty string.")
if (members.isEmpty) Fiber.abort("A group must have at least one member.")
if (members.count != values.count) Fiber.abort("There must be as many values as members.")
name = name + "_"
var s = "class %(name) {\n"
for (i in 0...members.count) {
var m = members[i]
var v = values[i]
if (v is String) {
s = s + " static %(m) { \"%(v)\" }\n"
} else {
s = s + " static %(m) { %(v) }\n"
}
}
var mems = members.map { |m| "\"%(m)\"" }.join(", ")
var vals = values.map { |v| (v is String) ? "\"%(v)\"" : "%(v)" }.join(", ")
s = s + " static members { [%(mems)] }\n"
s = s + " static values { [%(vals)] }\n"
s = s + "}\n"
s = s + "return %(name)"
return Meta.compile(s).call()
}
}
 
9,476

edits