Hi, I want to make class that has 2D sequence as one of its variables. This is the class:
type
CellValue = -1..1
Maze = object
width: int
height: int
grid: seq[seq[CellValue]] = @[]
I've already made a getter:
proc `[]`(self: Maze, i: int): seq[CellValue] =
return self.grid[i]
How can I make a setter the Nim way?
proc `[]=`(self: var Maze, i: int, v: seq[CellValue]) =
self.grid[i] = v
.For [] you likely should annotate the result lent that way if you do someCall(mySeq[0]) it does not copy.
Since this seems to represent a rectangular grid you may want to use https://github.com/avahe-kellenberger/seq2d
Thank you very much, it sound like a reasonable solution, however when i run:
maze[0][0] = 1
I get error:
Error: 'maze[0][0]' cannot be assigned to
This should work:
proc `[]`(self: var Maze, i: int): var seq[CellValue] =
return self.grid[i]
Alternatively, you can do
proc `[]=`(self: var Maze, i, j: int, v: CellValue) =
self.grid[i][j] = v
and then call it like maze[0, 0] = 1.