Just getting into Nim and coming from non-statically typed languages :) Thanks in advance for any advice!
I wanted to pack some proc into an array (so they're indexable by an integer) and this is what I came up with which did actually work. I would like to do it the proper "Nim" way though.
type
Action = proc(text: string)
let a_echo: Action = proc (text: string) =
echo text
var action = 0x60
var actions: array[0x60..0x69, Action]
for i in actions.low..actions.high:
actions[i] = a_echo
I did look at these for inspiration already: https://forum.nim-lang.org/t/2895, https://forum.nim-lang.org/t/2050
In your example, a_echo can be a regular proc definition. What you are doing is assigning an immutable variable a_echo to an anonymous procedure, which is of type Action.
You could also use fill from std/algorithm for initializing the actions array instead of doing a plain for loop
Thanks for the playground. I see what you did with defining the a_echo proc. I read back through some of Salewski's book (specifically https://ssalewski.de/nimprogramming.html#_procedure_variables). It looks like I was mostly just overthinking it.
Do you know (unrelated) if there's an elegant way to be able to do like a __repr__ on the proc? Here's the related compiler error:
/usercode/in.nim(13, 3) Error: type mismatch
Expression: echo act
[1] act: Action
Expected one of (first mismatch at [position]):
[1] proc echo(x: varargs[typed, `$`])
proc `$`(x: proc): string =
$typeof(x) & " = ..."