I'm trying to read a csv file at compile-time and convert it into a const table. I found this old thread. The code i'm using is as follows:
import std/[parseutils, strutils, tables]
static:
let v1 = "data.csv".slurp.splitLines
var v2 = newSeq[(string, uint)]()
for pair in v1:
let splitted = split(pair, ',')
if len(splitted) > 1:
v2.add((splitted[0], splitted[1].parseUint))
const v3 = v2.toTable
echo v3
Now i get the following error: undeclared identifier: 'v2'
Should have mentioned which nim version i use:
Nim Compiler Version 1.9.1 [Linux: amd64]
Compiled at 2022-12-22
Copyright (c) 2006-2022 by Andreas Rumpf
git hash: 18c115c8d0b38e6dbb7fae5bdda94bfca1a0ecef
active boot switches: -d:release
static opens its own scope, so outside of it the variable is not defined. You can instead use a static expression and assign it to a const variable like so (and in principle just directly call toTable instead of having v2 and v3 separately, unless you need v2 itself somewhere):
import std/[parseutils, strutils, tables]
const v2 = static:
let v1 = "data.csv".slurp.splitLines
var res = newSeq[(string, uint)]()
for pair in v1:
let splitted = split(pair, ',')
if len(splitted) > 1:
res.add((splitted[0], splitted[1].parseUint))
res
const v3 = v2.toTable
echo v3
(note that you could keep the name v2 inside of the static block, but I changed it for clarity)