Hello,
I am aware that astToStr returns string form of a Nim symbol or identifier.
I am looking to do the opposite of that.
I tried the below nim code but it fails with:
/home/kmodi/sandbox/nim/strToSymbol/t.nim(13, 12) template/generic instantiation of `createProc` from here
/home/kmodi/sandbox/nim/strToSymbol/t.nim(8, 26) template/generic instantiation of `strToSymbol` from here
/home/kmodi/sandbox/nim/strToSymbol/t.nim(4, 17) Error: undeclared identifier: 'auto_foo'
import std/[macros]
macro strToSymbol(s: static string): untyped =
result = ident(s)
template createProc*(procName: typed; body: untyped) =
const
procSym = strToSymbol("auto_" & procName)
proc `procSym`() =
body
createProc "foo":
echo "I am in foo"
auto_foo()
You were on the right track, you can just use a macro for this and it makes it so much simpler.
import std/[macros]
macro createProc(name, body: untyped): untyped =
result = newProc(ident("auto" & $name.baseName), body = body)
createProc foo:
echo "I am in foo"
auto_foo()
Thanks, I was fiddling around with that code and I came up with this:
import std/[macros]
macro createProc*(procName: static string; body: untyped) =
let
procSym = ident("auto_" & procName)
result = quote do:
proc `procSym`() =
`body`
createProc "foo":
echo "I am in auto_foo"
auto_foo()
This also works which may be more/less convenient:
template createProc*(procName: untyped; body: untyped) =
proc `auto procName` = body
createProc foo:
echo "I am in auto_foo"
auto_foo()
Note, the first template parameter needs to be untyped.