Skip to content

Instantly share code, notes, and snippets.

@oakes
Last active October 19, 2022 13:35
Show Gist options
  • Save oakes/958dddb06d37c564bb0ba3559f4f4195 to your computer and use it in GitHub Desktop.
Save oakes/958dddb06d37c564bb0ba3559f4f4195 to your computer and use it in GitHub Desktop.

Did you know nim can eval itself at runtime like a frickin scripting language?

Clone this gist and do...

nimble install compiler
nim c -r nimeval.nim

...and you should see:

Hello, dude!
The square of 10 is 100
proc sayHello*(name: string) =
echo "Hello, " & name & "!"
proc square*(n: int): int =
n * n
import compiler/nimeval
from compiler/ast import nil
import os
let std = findNimStdLibCompileTime()
let intr = createInterpreter("myscript.nim", [std, parentDir(currentSourcePath),
std / "pure", std / "core"])
intr.evalScript()
let helloProc = intr.selectRoutine("sayHello")
discard intr.callRoutine(helloProc, [ast.newStrNode(ast.nkStrLit, "dude")])
let squareProc = intr.selectRoutine("square")
let n = 10
let nSquared = intr.callRoutine(squareProc, [ast.newIntNode(ast.nkIntLit, n)]).intVal
echo "The square of " & $n & " is " & $nSquared
intr.destroyInterpreter()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment