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.

Revisions

  1. oakes created this gist May 4, 2021.
    15 changes: 15 additions & 0 deletions evaling_with_nim.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,15 @@
    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
    ```
    5 changes: 5 additions & 0 deletions myscript.nim
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,5 @@
    proc sayHello*(name: string) =
    echo "Hello, " & name & "!"

    proc square*(n: int): int =
    n * n
    18 changes: 18 additions & 0 deletions nimeval.nim
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    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()