Invalid set index '0' (on base: 'Array')

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By hidemat

Can anyone tell why this doesn’t work?

var arr = []

arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4

print(arr)

I get this error:

Invalid set index '0' (on base: 'Array') with value of type 'int'
:bust_in_silhouette: Reply From: Adam_S

You can’t set arr[0] because it doesn’t exist. (same for the next three lines)
Use arr.append(1) or one of the other methods to add something to an array.

Thanks. I suppose I could do something like var arr = range(4), but then I would get values in my array. Is there a short way to initialize my array with 4 null values?

hidemat | 2019-10-24 01:12

Sure just declare it like this: var arr = [null, null, null, null]

Adam_S | 2019-10-24 01:21

gotcha. thanks

hidemat | 2019-10-24 01:36

:bust_in_silhouette: Reply From: hidemat

Oh following your advice Adam_S, looking into the other methods available, the insert method seems to do the trick if you do this:

var arr = []

arr.insert(0,1)
arr.insert(1,2)
arr.insert(2,3)
arr.insert(3,4)

print(arr)

I was curious because I’m using an enum as the index to the array so if I had an enum like this:

enum SIDES {UP, DOWN, LEFT, RIGHT}

I could do something like this:

arr.insert(SIDES.UP, true)

Thanks for your help.

Edit: oh this also works

var arr = []
arr.resize(4)

arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4

print(arr)