I have a sequence of values that I know at compile-time, for example: const x: seq[string] = @["s1", "s2", "s3"]
I want to loop over that seq in a manner that keeps the variable a static string instead of a string as I intend to use these strings with macros later.
I can iterate on objects in such a manner using the fieldPairs iterator, but how can I do the same with just a seq?
A normal loop such as
for s in x:
echo s is static string
does not work, as s will be a string, which is not what I need.
The folks over at the nim forum were very helpful (here the thread).
The solution appears to be writing your own macro to do this. 2 solutions I managed to make work for me were from the users mratsim and a specialized version from hlaaftana
Hlaaftana's version:
This one unrolls the loop over the various values in the sequence. By that I mean, that the "iterating variable s" changes its value and is always the value of one of the entries of that compile-time seq
x(or in this examplea). In that way it functions basically like a normal for-in loop.mratsim's version:
This one doesn't unroll a loop over the values, but over a range of indices. You basically tell the
staticFormacro over what range of values you want an unrolled for loop and it generates that for you. You can access the individual entries in the seq then with that index.Elegantbeefs version
Similar to Hlaaftana's version this unrolls the loop itself and provides you a value, not an index.
All of them are valid approaches.