Hello,
I try to write a game, and i have a compilation issue with function declaration in a tuple.
type actionEnum = enum idle,look
type Mob* = object
name*:string
action*:tuple[ name:actionEnum, fx:proc(m:var Mob) ]
proc action_idle( m:var Mob)
proc action_look( m:var Mob)
var actions = [ idle:(idle, action_idle), look:(look, action_look) ]
proc action_idle( m:var Mob) =
echo "idle, now looking"
m.action = actions[look]
proc action_look( m:var Mob) =
echo "looking, time to rest"
m.action = actions[idle]
I get:
type mismatch: got <(actionEnum, proc (m: var Mob))> but expected 'tuple[name: actionEnum, fx: proc (m: var Mob){.closure.}]
So i understand it is related to call conventions ( {.nimcall.} or {.closure.} ).
The compiler wants a proc with closure calling convention.
So as i am not irksome, i have added {.nimcall.} to the tuple declaration, like this:
action*:tuple[ name:actionEnum, fx:proc(m:var Mob) {.nimcall} ] (magic!)
So now it's ok, at least it compiles, but i am not sure i'm doing things right by enforcing calling conventions.
Thank you for reading.
this is correct. when implementing a function table you should prefer {.nimcall.} to avoid the extra overhead of {.closure.}
while i don't know the rest of your logic, so maybe there's a reason you've structured things that way, but perhaps you might like to consider as an alternative:
type actionKind = enum akIdle,akLook
type Mob* = object
name*: string
action:actionKind
actions: array[actionKind,proc(m:var Mob)]
proc action_idle(m:var Mob)
proc action_look(m:var Mob)
proc initMob():Mob = Mob(actions: [akIdle: action_idle, akLook: action_look])
proc act(m:var Mob) = m.actions[m.action](m)
proc action_idle( m:var Mob) =
echo "idle, now looking"
m.action = akLook
proc action_look( m:var Mob) =
echo "looking, time to rest"
m.action = akIdle
benefits as i see them: no global state, no duplicating [idle:(idle:...]. adding a new action does still require you to a)update actionKind, b) add the new proc c)add it to initMob which could be errorprone, but this is what macros are for