# Help with Tables

Hello all. I am currently trying to make a recreation of space invaders for a class project and having trouble creating multiple invaders. I was wondering if anyone could give me an explanation of how tables work or just show me an example. Thanks!

Tap on the “Wiki” option under Codea Talk at the top of the forum. A there are a lot of tutorials there.

Just posted this on another thread actually…

Tables aren’t that hard, just think of them as a way of storing multiple values:

``````x = {"Hello ", "World!"}
print(x)
``````

So x is the table, and to get the nth index of that table you use [n] after the table.

I’m pretty sure you can store any values in a table.

There are two different ways you can use tables, as arrays, or as dictionaries.

In an array you can basically do what I did above:

``````x = {1, 2, 3, 4}
``````

Remember how you would say [n] to get the nth value of the array? In a dictionary you can control the indexes:

``````x = {["Hello"] = "Hi ", ["Earth"] = "World!"}
``````

Which can also be shortened with some syntactic sugar:

``````x = {Hello = "Hi ", Earth = "World!"}
``````

Thank you Lua So then you can do this:

``````print(x["Hello"])
``````

Or some more syntactic sugar!

``````print(x.Hello)
``````

You can also create new indexes after you make the table in 3 ways:

``````x[n] = "Hello"
table.insert(x, n, "Hello")
rawset(x, n, Hello)
``````

Aside from that Lua provides a whole table of different functionalities (we’ve already used one before)

The table is literally called just that, table.

Here’s a few main ones:

``````table.insert
table.remove
table.unpack
``````

Another important note to remember, is that tables are stored by reference not by value:

``````x = {}
y = x
--Any changes to x or y will change the other:
x = "Hi"
print(y)
--> Hi
``````

Looping through a table COULD be done with a normal for loop:

``````x = {"Hi ", "Planet ", "Earth"}
for I = 1,#x do
print(x[I])
end
``````

Or with pairs/ipairs:

``````for I,v in pairs(x) do
print(v)
end
``````

Important note: #x won’t work if x is a dictionary!

In the generic for loop used above, I is the index, v is the value.

Difference between pairs and pairs:

pairs: Ignores nil Indexes

ipairs: Stops at the first nil index it finds

If you have any questions don’t hesitate to PM me!

concerning integer index / text index: beware these caveats:
consider them as 2 independant sets of indexes: first integers, in growing order, then text, in random order.
`pairs()` scans all these indexes in above order.
`ipairs()` scans the integers from 1 to the n, n being the last integer without holes: if indexes are `1,2,3,5,6`then n=3!
`#myTable` is also 3 in the above example, not 6 nor 5. And if indexes are:`1,2,3,4,'hello','my','friend' `then it is 4, not 7!

Ok thanks @Jmv38 @warspykingand this was very helpful