Could someone explain tables to me?
- How do they work?
- What do they do?
- How can I use them? (Example codes)
- How they make my life eaiser ?
- How to use them ?
Thanks, AnthonyD98
myTable = {}
Now we have an empty table.myTable["name"] = "NeverCast"
print("Hello I am ".. myTable["name"])
This would print out Hello I am NeverCast …. Nice to meet you btw!table.insert(myTable, "hello world!")
Now 1 in the table has the value "hello world!"helloMessage = myTable[1]
print(#myTable)
print(myTable.name)
Tables are dictionaries/ arrays and everything that is awesome in programming, all rolled in to one!
Tables are basically a key value map. they connect a key, with a value. A key can be anything and the value can be anything. Including another table.
To create an empty table, just go like thisNow we have an empty table.myTable = {}
If we wanted the table to remember our name, we could go like thismyTable["name"] = "NeverCast"
Now the table has linked 'name' with 'NeverCast'. If we wanted to recall that later we can go like this.This would print out Hello I am NeverCast …. Nice to meet you btw!print("Hello I am ".. myTable["name"])
Tables can also be used as an array, If you've used arrays before, you know they store values and index them by a number.
In Lua, Arrays start at the number 1 ( not 0 like languages such as Java and C# )
If we wanted to easily add a value to a table we can use, table insertNow 1 in the table has the value "hello world!"table.insert(myTable, "hello world!")
We can recall it like this:helloMessage = myTable[1]
We can also see how many items are in a table by using a # before the table.
( Note: It only counts sequentially, 1,2,3 etc. It does not count us putting 'name' in to the table )print(#myTable)
That will print 1, as we added hello world!, Note how it does not say two even though 'name' is stored in there? That's because it only counts numbers as an array.
As you can see tables can be used for all sorts of things. You can also index them by using a dot. Like this!print(myTable.name)
Hope this helps get you started with tables! There are lots of tutorials on the internet that will be more helpful than me!
myTable = myTable[myTable]
Now I Really got dizzy when you talked about a table in a table and so on.. :P/>You're very welcome.
remember that arrays are just emulated using numbers as the key, so you can still go myTable[1] = value etc.
Also tables can take afaik, anything as a key, and anything as a value. So you can go myTable[myTable] = myTable
Now you can access your table through your table using your table as a key :P/>myTable = myTable[myTable]
But you wouldn't, cause that's crazy :D/>
Also when using myTable.someKey, It basically changes that to myTable["someKey"] at runtime. So you can only use strings in this dotting manner.
local strtable = textutils.serialize(sometable)
local file = fs.open('somefilepath','w')
file.write(strtable)
file.close()