0

I want to set a variable to the file path to include and then use that variable to include it I tried:

var path: string = "example.nim"
include path

This gives an error because it thinks the path I'm trying to include is "path" Basically I want to include "example.nim" when set to a variable value

1 Answers1

4

It is not possible to include file at runtime (like you can in python) because nim is a statically compiled language. You can, however write a macro that generates necessary include statement (though I would really advise against that unless you have very specific use case that requires such code):

import std/macros

macro makeIncludeStrLit(
  arg: static[string]): untyped =
  # ^ To pass value to macro use `static[<your-type>]`

  newTree(nnkIncludeStmt, newLit(arg))
  # Generates `include "your string"`

static:
  writeFile("/tmp/something.nim", "echo 123")

const path = "/tmp/something.nim"
# ^ path MUST be known at compile-time in order for macro to work.

makeIncludeStrLit(path)
haxscramper
  • 775
  • 7
  • 17