Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

What are Tables?

Asked by
lucas4114 607 Moderation Voter
8 years ago

I'm trying to find out how to use for loops but I really don't understand how tabels work. Can anyone just tell me what tabels are and do and how to make them?

0
It would help if you explain what aspect of tables you do not understand. Try reviewing this Wiki Article for information http://wiki.roblox.com/index.php?title=Table M39a9am3R 3210 — 8y

4 answers

Log in to vote
4
Answered by 8 years ago

Simple answer:

Tables are data structures used to store information for a later use. You can think of them as a container of variables with assigned values, much like your generic script environment.

Explained:

Tables are used to hold things that we normally wouldn't use ordinary variables for. This can include having a script return a certain set of data, or having a script store a certain set of data. However, it's important to note that tables are values just like numbers and strings are values (they're just different data types).

Knowing this, we can easily set up an empty table the same way we would any ordinary value. Using a generic variable like this:

local my_random_table = {} -- "{}" represents a new table value

The amount of data you choose to store in your table goes between the curly brackets we used to create it. Now, keep in mind there are many ways to insert a value in a table, and I'll go over that after explaining the table library

What is the table library?

The table library is that blue highlighted text you get in your script when you type table, like this:

print(table) -- "table" is highlighted blue, and will print the word "table" followed by it's memory address (the random alphanumeric code after it)

Now, because we have this built-in library predefined with the variable "table", it's important to know that we should avoid using the word "table" as a variable (same goes with all other built-in libraries). For instance, we shouldn't say something like this:

local table = {} -- this overwrites the built-in table library by assigning it an empty table value

Technically there's nothing wrong with doing this, however if we decide to access the "table" library later on in our code, we'll end up getting a bunch of errors.

Anyway, keeping all that in mind, the table library is actually a table itself. A table that contains functions we can use to make working with tables a bit easier (most of the time). These function include inserting values into tables (table.insert), sorting values in tables (table.sort), removing values from arrays (table.remove), etc. I'm not going to go over all the functions in this library, but if you'd like to check them out you should visit this page: http://www.lua.org/pil/19.html

How to use them?

One of the great things about tables are how simple they are. They're nothing more than a suit case used to hold any piece of information you decide to throw into it. Though, you should always keep organization in mind when storing things.

As we know from above, you create a table using 2 curly brackets: { to start one, and }to end it. The values you store inside the table should be separated with either a , or a ;. You could even use both at the same time if you wanted, but there's really no reason to. Here's how we could store 3 string values in a table:

-- Notice that I'm using "Table", which does not have a predefined value, whereas "table" does. This is because Lua is a case sensitive language.

local Table = {'string 1','string 2','string 3'}

-- Just for the sake of showing just how dynamic tables can be, I'll give a few more examples of how you can format tables:

-- Vertically styled tables
local Table = {
    'string 1',
    'string 2',
    'string 3',
}

-- Tables using semicolons
local Table = {
    'string 1';
    'string 2';
    'string 3';
}

-- etc
local Table = {'string 1';'string2';'string3'}

All those examples of tables from above are exactly the same. How you choose to format your tables is entirely up to you, as long as it's syntactically correct.

Different kinds of tables?

No, there aren't actually different types of tables (in it's literal term), however there are different kinds. These different kind of tables are known as dictionaries and arrays, and these terms are determined by how you store data in your table.

Array?

All arrays are tables, but not all tables are arrays.

All the table examples I've displayed above are known as arrays. An array is a specific kind of table that consist of only numeric keys. What's a numeric key? Let's look at another example:

-- Array with numeric keys
local Table = {'string 1','string 2','string 3'}

-- In this array, 1 = 'string 1', 2 = 'string 2', and 3 = 'string 3'

Using arrays, numeric keys automatically assign themselves as the number that represents the data's position in the table. This is why 1 = 'string 1', because 'string 1' is the first value in the table.

Indexing arrays?

Using the information from above, we can articulate that this is how we'd index an array to extract a value from it. When indexing arrays, you must use the square brackets followed by the index number that represents the numeric key. Sounds a bit complicated, but you get used to the terminology really fast. Here's an example of how we'd index an array:

local Table = {'string 1','string 2','string 3'}

-- Using the square brackets to index the array, and encasing the number "1" in them, tells our script to pull the first value from our table (array)

local FirstValueInTable = Table[1]

print(FirstValueInTable) -- > 'string 1'

-- Likewise, if we were to replace that number with "2", it would pull the second value from our array:

local SecondValueInTable =Table[2]

print(SecondValueInTable) -- > 'string 2'

This is what differentiates arrays from dictionaries. Arrays will ALWAYS have only numeric keys, whereas dictionaries have predefined keys (like variables).

Dictionary?

All dictionaries are tables, but not all tables are dictionaries.

A dictionary is a table format in which each key of the table is overwritten by the program to have a custom meaning. What does this mean? Let's take a look:

-- This is a dictionary. Notice how I transition from using a horizontal table format, to a vertical format. There's no special reason behind this, but most people find the vertical style table to fit better when using dictionaries.

local Dictionary = {
    Hello = "Hi",
    There = "There",
    Bye = "goodbye",
}

-- Note: we have no numeric keys in this table. Our keys in this table are: "Hello", "There", and "Bye". All in which overwrite the default numeric keys (making it not an array).

-- Side note: saying something like this is exactly the same as above, just written differently:

local Dictionary = {Hello = "Hi", There = "There", Bye = "goodbye"}

Indexing dictionaries?

You may notice that when you want to find a part in the workspace of your game, you're using the dot . symbol to do so. This is because all references to your game inside your script, is actually just one big dictionary. Keeping that in mind, we use the same . symbol to index dictionaries in tables, just as we do to get objects from our game. Like this:

local Dictionary = {
    Hello = "Hi",
    There = "There",
    Bye = "goodbye",
}

print(Dictionary.Hello) -- Gets the "Hello" key from our dictionary (which equals "Hi"), and prints it. This will print "Hi".

print(Dictionary.There) -- Again, gets the "There" key from our table (which is equal to "There"), and prints it.

Finally, for loops.

I'm gonna try not to make this explanation about for loops, since this is already a pretty long answer. So if you're still new to for loops, I recommend these sites:

http://wiki.roblox.com/index.php?title=Loops#For

http://www.lua.org/pil/4.3.4.html

http://www.lua.org/pil/4.3.5.html

Iterating your table

Back to the explanation on indexing arrays, you may notice that repeating the same code over an over again with just changing the index number in each variable can get very tedious (and messy). However, this is something the numeric for loop is very good (and efficient) at.

You could also make sense out of using a numeric for loop to iterate an array, since all keys of an array are numbers. Here's an example of printing all values in an array:

local Array = {"Hello","my","name","is","bob"}

-- Something else you should always know, is that we can use the "#" symbol before an array to get it's length (how much data is inside the table). Here's an example:

print(#Array) -- > 5 (prints 5 because there are 5 string values inside our array)

for i = 1,#Array do -- this will loop 5 times (starting with 1)

-- remember, 'i' is the variable that changes every iteration. The first loop, i = 1, the second loop, i = 2, third loop i = 3, and so on. This is extremely useful since now we can just use 'i' as our index number to get all values in the array.

    print(Array[i])
end

Output:

Hello

my

name

is

bob

Can't get length of a dictionary?

In the example above, I stated that you can use the # symbol before an array to get it's length. However, this will not work for dictionaries. That's because dictionaries have no numeric keys. If you'd like to know more about how to solve that problem, I'd suggest reading the end of this answered question: https://scriptinghelpers.org/questions/25853/how-to-pick-a-random-string-from-a-table#29441

Hope this helped, I'll most likely be updating this post a lot, so if there's anything you need help on, just let me know.

0
In the wiki I've seen different for loops. Some are like the ones you said "for something, number, number2 do" then some using 'in', "for something, something2 in something3(something4)" and theres alot in pairs and ipairs, "for something, something2 in pairs(something3) do" and "for something, something2 in ipairs(something3) do" What do there do? lucas4114 607 — 8y
Ad
Log in to vote
2
Answered by 8 years ago

"Sadly, programming tables can't hold drinks." -@M39a9am3R

"ur so slow table = {"drinks"}" -@koolkid8099

Tables are fancy dancy nancy zancy bancy pancy tancy ways to store, well, things!

To declare a table, you need to do this:

local table = {} --Fancy brackets for a fancy table

That looks useless, for now, at the moment it is a very empty table, which is disappointing. BUT WAIT WHAT IF WE DO THIS????

local table = {"hi im a banana"}

WOAH MAGICAL RIGHT?

no?

well, that would be the answer I expected because you don't know what just happened, but don't fret, you will soon!

Basically, what we did there is make a table, easy enough, but then we have a value in the table!

It's basically like putting some food on a real life table, but instead of food, we inserted information into the table!

Okie, that's cool and all, but how do we access it??

Well, values in tables have a key!

Keys depend on what type of table it is, an array or a dictionary, for this answer, we're talking about arrays.

Keys are numbers in arrays, if we do this:

local table = {"hi", "cool"}
print(table[1]) -->hi

It's telling Luato get the value with the key of 1!

Basically values are like doors and to access them you need keys.


This just got confusing. Tables are tables with doors that need keys? Wow, I do tend to overcomplicate things!

Oh well, I hope you learned a thing or two from this answer!

Log in to vote
1
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
8 years ago

Lua has values like numbers 15 or strings "cat". But if you want something to have two values, e.g., a name and a worth, you want to have one place to put those things.

Tables are objects that group many values together.

They have two main "modes" of operation (this isn't strict, you can mix them together):

Lists

A list is an ordered collection of values. A list has a 1st element: list[1], a second element: list[2]. The nth element is list[n].

A list is defined by {}. Inside the {} are comma-separated-values. For example, the list of the first few elements could be defined as

elements = {"Hydrogen", "Helium", "Lithium", "Beryllium", "Boron"}

There are #list things inside list. Thus the last element is the #listth thing, so list[#list].

This mapping of 1, 2, 3, ..., #list makes it very easy to go over lists with for loops. It will usually look like this:

list = {2, 3, 5, 7, 8}
for i = 1, #list do
    print("The " .. i .. "th thing is " .. list[i])
end
-- OUTPUT:
-- The 1th thing is 2
-- The 2th thing is 3
-- The 3th thing is 5
-- The 4th thing is 7
-- The 5th thing is 8

If you do a lot with list[i], it can be a bit repetitive. There is a built-in iterator called ipairs that you can use to help with this:

for i, thing in ipairs(list) do
    print("The " .. i .. "th thing is " .. thing)
end
-- (same output)

Maps

A map associates some key with some value.

For example, this map associates some states with their capitals:

StateCapital = {
    ["Alabama"] = "Montgomery",
    California = "Sacramento",
    ["New York"] = "Albany",
    Washington = "Olympia",
}

Maps are defined again with {} and have their entires comma separate. It looks like either keyName = value or [key] = value. That is, ["keyName"] and keyName are interchangeable here.

To get or set the thing at a particular key, use map[key].

Realize that lists are just maps from the counting numbers to things.

There isn't a "first" key in a map like there is in a list, since any value (except nil) can be used as a key.

Thus, to search through a map, you can use pairs:

for state, capital in pairs( StateCapital ) do
    print("The capital of " .. state .. " is " .. capital)
end

Note that the order that this goes through is indeterminate (essentially random). It also works on lists, but, again, the order is random.

Log in to vote
0
Answered by 8 years ago

tables are a way of storing information. To use tables in a loop you would have to use a i,v pair loop. Tables are made simple by using {}. Here is a example

table = {"Derp","Derp2","derp3","pie"} --Here i created a table to store information

for i,v in pairs(table) do -- Now i have created a loop that will go through the table called "table"
    print(v) -- I printed v which should print something from my table depending on where its at
-- [[V is the variable that the loop is currently on as it goes down the list. This can be changed to --whatever you want]]
end
0
But what's the "i"? lucas4114 607 — 8y
1
i is just the index in which it cycles through the table. This is important but not really, its just the way it counts it way through the table koolkid8099 705 — 8y
0
ty lucas4114 607 — 8y

Answer this question