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

How does a table work? I know how to write one, but I do not understand how it works.

Asked by 5 years ago
local basket = {"apple","apple, "orange", "apple",
"orange", "orange"}
for num, item in pairs(basket) do

print(num, item)

if item == "apple" do
print"cut apple"
elseif item == "orange" do
print"peel orange"
   end
end 

I know what it prints (I have run the code) 1 apple cut apple 2 apple cut apple 3 orange peel orange 4 apple cut apple 5 orange peel orange 6 apple cut apple I do not understand any of the code in this block.

1
forgot closing parenthesis on the second "apple". ACDCMASTA -1 — 5y

1 answer

Log in to vote
1
Answered by
Jexpler 63
5 years ago

A table is basically a variable that stores multiple values. Basket contains the string (test) values of apple and orange. They then used a for loop. Basically it will run a few lines of code (line 4 - 11 in this case) every time for the index. Because they used in pairs(table name) it used the number of items in the table as the index. So it runs the loop once for every item in the table. It checks if the value it's running the loop in is an apple or an orange. If it equals an apple (if item == "apple") or if it's an orange (elseif item == "orange"). Hope this clears it up.

Ad

Answer this question