In this code:
var myPtr: ptr Widget
var myIndex: int
for element in widgetArray:
myPtr = element.addr # Bad, takes the address of a loop-local reference
for index, element in widgetArray.toOpenArray(0, widgetArray.high):
myPtr = element.addr # Bad, same reason
for element in widgetArray.toOpenArray(0, widgetArray.high):
myPtr = element.addr # Ok, takes the address of the array element
myIndex = cast[int](element.addr) - cast[int](widgetArray[0].addr)) / sizeof(Widget)) # Pointer arithmetic I would like to avoid
for index, element in widgetArray:
myPtr = element.addr # Bad
myPtr = widgetArray[index].addr # Ok
myIndex = index
The difference between those different cases is surprising. This example is an useless way of taking the address of the last element, but I had the problem of having to store a reference to a loop element that outlives the current loop iteration, and take it’s index. The last loop is the least convoluted way to have both.
Is there a better way to do this?
Checkout mitems iterator: https://nim-lang.org/docs/iterators.html#mitems.i%2Carray%5BIX%2CT%5D
It gives a var T that should let you take the addr of.