|
|
|
|
|
by filwit
4068 days ago
|
|
> can static: sections assign to an array that will be available at runtime? The answer is yes, but it's a tad trickier than just accessing the compile-time list from run-time code (which doesn't make sense, and is illegal). Instead, use a macro to generate a bunch of run-time checks against a specific value. Eg: var eventNames {.compileTime.} = newSeq[string]()
proc defineEvent(name:static[string]) =
static:
eventNames.add(name)
macro checkDefined(name): stmt =
# begin new statement
result = newStmtList().add quote do:
echo "Checking for '", `name`, "'"
# loop over every known event name and
# build a run-time 'if' check for each one.
for n in eventNames:
result.add quote do:
if `n` == `name`:
echo "Found it!"
# add some events to compile-time list
defineEvent("foo")
defineEvent("bar")
# define some runtime values
let eventName1 = "foo"
let eventName2 = "blah"
# check runtime values againts compile-time list
checkDefined(eventName1)
checkDefined(eventName2)
# output:
# Checking for 'foo'
# Found it!
# Checking for 'blah'
Note: This will inject a bunch of 'if' statements for each call to 'checkDefined', which might bloat your code.. it's probably better to make a macro which defines a proc, then just call that to check run-time values.. but I left those kinds of details out of this illustration for the sake of simplicity. |
|