type
Rows = 0..32
Cols = 0..32
Coord = tuple[row: Rows, col: Cols]
. . .
Cell = object
doors : Doors
Grid = ref GridObj
. . .
proc cN(g: Grid, row: Rows, col: Cols): Coord =
try:
let c: Coord = (row: row - 1, col: col)
result = c
except:
raise newException(IndexError, "Attempt to move too far North")
results in error:
. . . (60, 24) Error: type mismatch: got (tuple[row: range -1..31(int), col: Cols]) but expected 'Coord'
Process terminated with exit code 256
I first tried to avoid this with an if test. How should I handle this? All I can think of is expanding the range to include an illegal value.
let newRow: Rows = max(row-1, 0)
result = (newRow, col)
# Or even shorter:
result = (Rows(max(row - 1, 0)), col)
I guess using 3 spaces for indentation is a compromise between 2 and 4? :P
let c: Coord = (row: Rows(row - 1), col: col)
or use in context where it's definitely valid and compiler can see it:
if row > 0:
let c: Coord = (row: row - 1, col: col)
result = c
proc cN(g: Grid, row: Rows, col: Cols): Coord =
if row > 0:
let c: Coord = (row: row - 1, col: col)
result = c
else:
raise newException(IndexError, "Attempt to move too far North")
and got:
. . .(60, 24) Error: type mismatch: got (tuple[row: range -1..31(int), col: Cols]) but expected 'Coord'
Process terminated with exit code 256
That's the "let" statement.
However, combining suggestions:
proc cN(g: Grid, row: Rows, col: Cols): Coord =
if row > 0:
let c: Coord = (row: Rows(row - 1), col: col)
result = c
else:
raise newException(IndexError, "Attempt to move too far North")
lets me get to a routine I'm still writing that will use this proc. (Currently the message is "Invalid Indentation", but what it really means is that the proc ended before the body of a for statement.)
Thanks.
Indeed, doesn't work with just if.
It seems the best is just to declare the argument as 1..32, what it is intended to be. And this works.
proc cN(g: Grid, row: 1..32, col: Cols): Coord =
if row > 0:
let c: Coord = (row: Rows(row - 1), col: col)
result = c
else:
raise newException(IndexError, "Attempt to move too far North")
let r: Rows = 2
echo cN(nil, r, 7).repr