我如何通过变量值包含文件

问题描述

我想为要包含的文件路径设置一个变量,然后使用该变量来包含它 我试过了:

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

这会产生错误,因为它认为我尝试包含的路径是“路径” 基本上我想在设置为变量值时包含“example.nim”

解决方法

不可能在运行时 include 文件(就像在 python 中一样),因为 nim 是一种静态编译语言。但是,您可以编写一个宏来生成必要的 include 语句(尽管我真的不建议这样做,除非您有非常具体的用例需要此类代码):

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)