I know Nim has support for static blocks, but I do not know what they can be used for, except from printing hello world at compile time, like it is written in the example. I was hoping I could create some code in them, but I do not know where to put the ast that I generate:
import macros
static:
let ast = quote do:
echo "hello world"
# what can I do with ast now, except from discarding it?
Is it possible to make the static block evaluate to echo "hello world", that then gets evaluated at runtime again?
Is it possible to make the static block evaluate to echo "hello world", that then gets evaluated at runtime again?
Just to call one and the same code at compile- and at run-time? This?
template hw = echo "hello world!"
static:
hw()
hw()
EDIT
Regarding usefulness: yet another compile-time hello world with very basic compile-time reading of ini-file (w/o sections, comments only starting at line beginning) into const table.
import strutils, tables
static:
let c="test.conf".slurp.splitLines
var a=newSeq[(string,string)]()
for v in c:
if v.len>0 and v[0]!=';':
let vv=v.split('=')
add a, (vv[0].strip.toLowerAscii, vv[1].strip)
const conf=a.toTable
# having the config is smth like
# h = hello
# ; comments allowed; keys may be in either case, they will be lower-cased
# W = world
echo t["h"] & ", " & t["w"] & "!" # -> hello, world!
Many things don't work in VM, say json or parsecfg won't work, still it can be of use.
@LeuGim thanks for your effort, sadly it is not really what I was hoping for. I was hoping it could be used as an inplace macro. This is what I mean:
macro makeHelloWorld(): untyped =
result = quote do:
echo "Hello Wolrd!"
makeHelloWolrd()
imagine a lot of macros like this. Each of them executed exacty once, and always right after definition. So I thought maybe the static block could simplify the code, and remove the need to always come up with new identifiers:
static:
result = quote do:
echo "Hello World!"
but that is sadly this is not a simplification that can be applied.