type
Sel = enum
one, two
var
select: Sel
# Set s from f(str)
proc init(s: var Sel, str: string) =
# <str> = f(str)
# === preferably not:
# case <str>
# of "one": s = one
# of "two": s = two
# === preferably not:
# let tab: Table[string, Sel] = {"one": one, "two": two}.toTable
# s = tab[<str>]
# === preferably:
# s = some_macro(<str>)
...
init(select, "xx:two")
case select
of one: echo "ONE detected"
of two: echo "TWO detected"
Consider e.g. the maintenance necessary when adding three, and four to Sel.
import strutils
type Sel = enum one, two
var select = parseEnum[Sel]("two")
echo select
@def
It would be great if I could create and use enums on the fly, e.g. like this:
some_proc("optOne:...@optTwo:...@...") =
...
resulting in:
enum some_name = optOne, optTwo, ...
...
case
of optOne: ...
of optTwo: ...
Can that be achieved with macros?
some_macro("optOne:...@optTwo:...@...")
case
of optOne: ...
...
would be expected to be equal to:
enum some_enum optOne, optTwo, ...
case
of optOne: ...
...
@axben How about something like this:
import macros
macro stringToEnum(name: string, options: string): stmt =
parseStmt("type " & name.strVal & " = enum " & options.strVal)
stringToEnum("test", "one, two, three")
#type test = enum one, two, three
var x:test = one
case x:
of one: echo "one"
of two: echo "two"
of three: echo "three"
This is the easiest way I can imagine and of course you can work on that string inside the macro to transform the input to the wanted enums.
You could also generate the whole enum AST by yourself. That had to look like the output of this:
import macros
dumpTree:
type test = enum one, two, three