Gotchas
Iterating over empty arrays
This behaviour is in the user guide, but it’s not what I was expecting, so I thought I’d mention it. I expected that the following loop would not be executed when the array is empty,
as it’s a For 1 To 0 loop.
For [ Variable:%idx Items:1:%array(#) ]
End For
Actually, it runs twice with %idx equal to 1 and then 0. To have the loop skipped, set the iteration value to 1, like this.
For [ Variable:%idx Items:1:%array(#):1 ]
End For
Or of course, you can use a For Each loop.
For [ Variable:%var Items:%array() ]
End For
Popping Arrays
It’s a fairly common programming practice to iterate from the end of an array to the start to pop some of the elements. By traversing backwards you don’t mess up the index positions
in the array. However, if you do this with Tasker, weird things happen. If you run the following code, you would expect to see “spider,ant,bird,fish 8-7-6-5-4-3-2-1-”
Array Set [ Variable Array:%animals Values:cat spider ant dog mouse bird horse fish Splitter: ]
Array Set [ Variable Array:%mammals Values:dog horse cat mouse Splitter: ]
For [ Variable:%idx Items:%animals(#):1:-1 ]
Variable Set [ Name:%iteration To:%idx- Append:On ]
Variable Set [ Name:%animal To:%animals(%idx) Append:On ]
Array Pop [ Variable Array:%animals Position:%idx To Var: ] If [ %mammals(#?%animal) != 0 ]
End For
Flash [ Text:%animals() %iteration ]
What you actually see is “spider,ant,dog,bird,fish 8-7-5-3-2-1-” Weird, the start variable should not affect the loop in mid cycle, but it does. Here is a work round:
Array Set [ Variable Array:%animals Values:cat spider ant dog mouse bird horse fish Splitter: ]
Array Set [ Variable Array:%mammals Values:dog horse cat mouse Splitter: ]
Variable Set [ Name:%start To:%animals(#) ]
For [ Variable:%idx Items:%start:1:-1 ]
Variable Set [ Name:%iteration To:%idx- Append:On ]
Variable Set [ Name:%animal To:%animals(%idx) Append:On ]
Array Pop [ Variable Array:%animals Position:%idx To Var: ] If [ %mammals(#?%animal) != 0 ]
End For
Flash [ Text:%animals() %iteration ]
JavaScript Arrays
This code flashes “dog” as you would expect.
Array Set [ Variable Array:%array Values:cat dog horse Splitter: ]
⋮
JavaScriptlet [ Code:var two = array[1]; ]
Flash [ Text:%two ]
However this code flashes “u” It’s the second character of the base variable of the array.
Array Set [ Variable Array:%array Values:cat dog horse Splitter: ]
Variable Set [ Name:%array To:ouch ]
⋮
JavaScriptlet [ Code:var two = array[1]; ]
Flash [ Text:%two ]
Work round: Make sure the base of the array is not set, thus -
Array Set [ Variable Array:%array Values:cat dog horse Splitter: ]
Variable Set [ Name:%array To:ouch ]
⋮
Variable Set [ Name:%base To:%array ]
Variable Clear [ Name:%array ]
JavaScriptlet [ Code:var two = array[1]; ]
Variable Set [ Name:%array To:%base ]
Flash [ Text:%two ]