Array is ok with index -1
-
I got into some array juggling in my code, more then I wanted, as usual and tried to find my way out. I almost started to believe in the ghost in my switch, because the program was running but the result did not make sense. - yes, all my fault, but have a thought about it:
a = [1,2,3] print(a[-1]) sleep(10)
Results in the output:
3
Maybe put a note in the array section of the help.
PS: I went through the forum to find something according "negative array indexes" but was not lucky, so I decided to post this. -
So does -2 output 2?
-
@Retrocade_media interesting question. I just checked, yes: -2 results in 2, -3 results in 1 and -4 results in:
Array index out of bounds. (Array size: 3, index: -1)
hmm.. -1 seems to indicate "too negative".
-
@spikey interesting. So using negative values just counts from right to left (or from the end to the beginning) of the array. It makes sense that you can only go so far. I wonder what uses this could have if any?
-
I found something cool: you can rotate through the array without any if checkings!
I havea = ["a", "b", "c"] i = -9 fixedIndex = i % len(a) print(a[fixedIndex] sleep(3)
prints:
a
instead of doing:
MAX = 2 MIN = 0 a = ["a", "b", "c"] i = -9 // the index can be increased or decreased in the program by a user input if i < 0 then i = MAX endif if i > MAX then i = MIN endif print(a[i]) sleep(3)
@FUZE Team Is that feature save for the future?
-
Would need one of the devs to respond but my suspicion is that you are just finding unsupported behaviour that is a side effect of the way things happen internally.
Essentially stick to this general rule of thumb: if it's not in the documentation then it's unsupported or unintended and 1) could break things (even resulting in data loss), 2) could be removed at any time and 3) could behave differently at any time.
Obviously every now and again there is the odd time where something genuinely get's ommitted from the documentation but that's the exception to the rule and we'll try to make people aware of it.
-
The documentation needs a couple of updates, but this is an intended feature. You've done a great job there @spikey discovering the ins and outs. Expect help documentation to come which reflects this!