Before you can assign stuff to tables, you have to create them first. There are two ways to do that:
wont work since there is no mytable existing yet, and hence mytable[1] cannot be accessed.
way 1:
Code: Select all
mytable = {}
mytable[1] = "myvalue"
FIrst empty mytable was created, then to index spot 1 value "myvalue" was assigned, this works fine.
way 2:
This one works as well. Now you are at same time creating the table, as well as telling what should be at index spot 1.
By knowing this you can now get on to multidimensional table:
wrong way:
Code: Select all
mytable = {[1] = "myvalue" }
mytable[1][2] = "myvalue"
wont work since mytable[1] is value, not a table. To be able to use mytable[1] as a table, and then being able to access mytable[1][2], you first need to make it as a table.
Another wrong way:
Code: Select all
mytable[1] = {}
mytable[1][2] = "myvalue"
You thought you are making mytable[1] as a table, but it wont work, since you are trying to make a table under a non existing table, you first need to make mytale before you can make mytable[1]
first way:
Code: Select all
mytable = {}
mytable[1] = {}
mytable[1][2] = "myvalue"
works. Now you first made mytable, and under mytable index spot [1] you made another table. Therefore you were able to put to index spot [2] of this new table a value "myvalue".
second way:
Code: Select all
mytable = { [1] = { [2] = "myvalue" } }
easier to read version:
Code: Select all
mytable = {
[1] = { [2] = "myvalue" }
}
These two are identical from hollywoods point of view.
In these two, you are both creating mytable as well as mytable[1] and putting "myvalue" at index spot [2] of mytables subtable[1].
This can naturally continue as far as you want:
Code: Select all
mytable = {}
mytable[1] = {}
mytable[1][2] = {}
mytable[1][2][3] = {}
works.
Just remember not to skip:
Code: Select all
mytable={}
mytable[1]= {}
mytable[1][2][3][4] = {}
wont work because tables mytable[1][2] and mytable[1][2][3] dont exist yet.
Notice also, that if you have more index spots with subtables, they all need to be created:
Code: Select all
mytable = {}
mytable[1] = {}
mytable[2] = {}
mytable[3] = {}
mytable[2][5] = "myvalue"
mytable[4][1] = "mysecondvalue"
"myvalue" is assigned correctly, since mytable[2] exists and it is now assigned to index spot 5 "myvalue" value.
"mysecondvalue" doesnt work, since it is trying to access mytable[4] table, which doesnt exist, as mytables were only made up to 3 index spots.