On Wednesday, 9 February 2022 at 08:12:52 UTC, Vindex wrote:
> Will the loop (foreach) run at compile time? How can I make it work at compile time?
import std.csv, std.stdio;
alias Record = Tuple!(string, string, string);
immutable string[][] table;
shared static this() {
string csvText = import("file.csv");
foreach (record; csvReader!Record(csvText)) {
table ~= [record[0], record[1], record[2]];
}
}
void main() {
writeln(table):
}
It will not run at compile-time because csvText is a runtime variable. It should be enum to be accessible at compile-time.
The second issue is that your foreach should probably be static foreach.
The third issue is how you're creating "table". The append operation will be executed at runtime, which means that even if the loop runs at compile-time then you're effectively not winning anything and it basically just becomes a loop-unroll manually done.
The solution would be to create a function that returns a string that is equivalent to the contents of the array you want to create, as if you wrote the content yourself.
And then simply using mixin to "set" the value of the table by calling that function.
Ex.
string getInt() { return "immutable a = 10;"; }
mixin(getInt);
// The variable a is accessible here ...