Why are you trying to use dynamic variables for this?
There are several obvious alternatives which are cleaner and less error-prone. If you use an Array (e.g.
[{key: "a", action: "1"}, ...]), it automatically has a defined length that could be used to limit
Loop. If you use an Array or Map, a for loop can give you all of the items without requiring you to check when you've reached the end. Even defining hotkeys one to a line in a continuation section, or in an INI file would work; Loop Parse can give you the lines that exist, without requiring you to terminate the loop explicitly.
None of these methods would require creating two (global) variables for each hotkey or explicitly numbering each hotkey. What if you want to remove or comment out a hotkey in the middle of the list?
swagfag wrote:if at the time of the invocation, [...] ud get an error... which is exactly what u got.
You're talking about errors that might be raised by the fat arrow function, but that is not what is going on at all. This script produces an error at the dynamic variable reference
key%A_Index% outside the closure. Once that is fixed, it does not produce an error.
This is correct, and close to the problem:
closures capture variable references, not values.
(*) => (Action(action%i%)) works similarly to
((&i, *) => (Action(action%i%))).Bind(&i).
But it is of only very limited relevance, because there are no closures in this script.
viv wrote:; key5 Variable not found.
If you must, use try/catch.
viv wrote:;all action%i% is 4
If all of this code was within a function, the
variable i (not its current value) would be captured by the closure. In this case there is no closure, just a fat arrow function referencing a global variable. Either way, by the time the closure is called,
i has the value that it was
last assigned (4).
The two solutions suggested by swagfag are correct. Both can be done with => or a full function.
((i, *) => Action(action%i%)).Bind(i)
((i) => (*) => Action(action%i%))(i)
But this is not efficient. If you need to account for
action%i% changing at runtime, resolve it to a VarRef (only once, when the hotkey is defined, not every time it is activated):
((&v, *) => Action(v)).Bind(&action%i%)
If the action value never changes at runtime, resolve it to a value.
((a, *) => Action(a)).Bind(action%i%)
((a) => (*) => Action(a))(action%i%)
But I would still recommend learning to avoid dynamic variables.