I want to assign unique numbers to consts, something like a primitive unique id. Something that enables:
const a = magicalProc() const b = magicalProc() doAssert(a==0) doAssert(b==1)
So far I tried implementing it with:
proc magicalProc(): int =
var counter{.global.} = 0
result = counter
counter += 1
but that works only when assigning to let, not to const:
block: let a = magicalProc() let b = magicalProc() doAssert(a==0) doAssert(b==1) block: const a = magicalProc() const b = magicalProc() doAssert(a==0) doAssert(b==0) # well, too bad
Is there a way to get the desired behavior?
It might be a bug with the global pragma. This works:
# have to mark this explicitly as a compile time var so the Nim compiler understands
var counter {.compileTime.}: int
proc magicalProc(): int =
result = counter
counter += 1
block:
const a = magicalProc()
const b = magicalProc()
echo a # Prints 0
echo b # Prints 1
Just for completeness sake, this also works:
proc magicalProc(): int {.compileTime.} =
var counter {.global.}: int
result = counter
counter += 1
block:
const a = magicalProc()
const b = magicalProc()
echo a # Prints 0
echo b # Prints 1
Essentially it boils down to how Nim treats compileTime and global together. But I agree that this might be a bug..
This works
proc magicalProc(): int =
var counter {.global compiletime.}: int
result = counter
counter += 1
block:
const
a = magicalProc()
b = magicalProc()
echo a
echo b
let
a, b = magicalProc()
echo a
echo b
#0
#1
#0
#1
though be aware that counter is essentially a seperate variable at runtime vs compiletime.