I'm trying to modify a sequence in-place by modifying the values without copying the data.
This worrks, but I wonder wether I'm doing it in an idiomatic 'Nim' way, rather than trying to use ptr too much.
I feel the answer should be here, where it is suggested to use ref. Not sure how to get that working tho: https://forum.nim-lang.org/t/6457
tl;dr In the code below, I expect that I should use ref seq[Vertex] while ptr is meant for interfacing with C and such. Is that correct, and if so, how to modify the snipppet of code?
types
type
Int32x2 = array[2, int32]
Vertex* = Int32x2
Polygon* = object of RootObj
vertices*: seq[Vertex]
fill*: LCDPattern
code
proc loadPolygon(level: Level, obj: LevelObjectEntity): bool =
let objOffset: Vertex = [obj.x, obj.y]
var polygon: Polygon = obj.getPolygon()
var vertices: ptr seq[Vertex] = addr polygon.vertices
let lastIndex = vertices[].high
if lastIndex < 2:
return false # polygons require at least 3 vertices
# Offset the polygon by the object's position (localToWorld)
for i in 0..lastIndex:
vertices[i] = vertices[i] + objOffset
[..]
It's not clear from this snippet what are getPolygon() and LevelObjectEntity really are and what they do.
But idiomatic code would look something like this:
type
Vertex* = tuple[x, y: int32]
Polygon* = object of RootObj
vertices*: seq[Vertex]
fill*: LCDPattern
proc loadPolygon(level: Level, obj: var LevelObjectEntity): bool =
let objOffset: Vertex = (obj.x, obj.y) # tuple instead of array
var polygon: Polygon = obj.getPolygon()
let lastIndex = polygon.vertices.high
if lastIndex < 2:
return false # polygons require at least 3 vertices
for vertex in polygon.vertices.mItems:
vertex += objOffset # or `vertex = vertex + objOffset`
1. var argument modifier makes obj mutable (passes the pointer to it internally). If LevelObjectEntity is already a ref/ptr type - then var is optional, but it still shows your intention to modify the object.
I was hoping to learn about something like mitems
Excellent answer, thank you!