My end goal at the moment is to be able to iterate over all of a tuple's fields, in order to generate values for them through a procedure, such that I can add or remove new fields in the future without having to rework elsewhere, like below.
type
tupp = tuple
rock:int
samba:int
jazz:int
proc generateValues(): tupp =
var o1:tupp
for ix in o1.fields(): #error line
o1[ix] = rand(10)
return o1
## Compilation will fail with "D:\nim-dev\tuplss.nim(9, 13) Error: cannot evaluate at compile time: o1"
## However, changing o1[ix] = rand(10)
## to echo ix compiles successfully and will iterate 3 times on the echo, though it always prints 0
However, all my attempts to iterate over a tuple or object's defined fields, using the fields() procedure have failed. Can someone explain why I'm getting the error "cannot evaluate at compile time" if the tuple's size is static (known at compile time)?
With the following code:
type tupp = tuple[rock:int, samba:int]
var t1:tupp
echo fields(t1) # or t1.fields()
Compilation fails with the following messages:
D:\nim-dev\tuplss.nim(3, 12) Error: attempting to call routine: 'fields'
found iterators.fields(x: T: tuple or object) [iterator declared in D:\nim-2.2.4\lib\system\iterators.nim(284, 10)]
found iterators.fields(x: S: tuple or object, y: T: tuple or object) [iterator declared in D:\nim-2.2.4\lib\system\iterators.nim(296, 10)]
Compilação falhou.
From my understanding, the compiler thinks both overloaded methods could apply, despite me passing only one parameter (x), not two (x, y). What's the correct way to call/use the fields iterator? My internet searching didn't lead to any quite similar problems.
I'm aware that something similar to a Dict, an array with keys that I can use to find specific positions, would also work, so it seems that using std/json is the easiest solution for my end goal.
It's just:
type
tupp = tuple
rock:int
samba:int
jazz:int
proc generateValues(): tupp =
var o1:tupp
for ix in o1.fields(): #error line
ix = rand(10)
return o1
Without the tuple indexing operation.
Ah, the iterating variable, ix in my case, represents the current field itself, that makes sense. Thanks, Araq!
I suppose the error with calling fields outside a for loop happens because the procedure is exclusive for iteration, correct?
I suppose the error with calling fields outside a for loop happens because the procedure is exclusive for iteration, correct?
Correct.