Can someone explain to me what this loop is , I saw it in some code.
for i = 1, #table do
#table
is just the number of things inside the table, it’s basically the same as saying
for i = 1, 5 do
assuming you have 5 things in the table
Is the # significant at all? Like does it do anything?
Yes, #table
returns the number of items in the table, while table
returns the table itself
#table
gives the length of table
.
If table = {2, 5, 6, 10, 0}
, then #table
= 5.
Also, I would suggest naming your table tbl
instead of table
because table
is a built-in library.
So will the loops run the same amount of times as the amount of variables in the table?
Yes, so if you had 5 things inside of the table such as:
local myTable = {
"Banana",
"Orange",
"Apple",
"Carrot",
"Tomato"
}
print(#myTable) --> 5
for i = 1, #myTable do
print("Apples are nice") --This would print 5 times
end
for i = 1, 5 do
print("Apples are nice") --This would also print 5 times
end
The # is the length operator of lua, it can return how many letters are in a string by measuring how many bytes are in the string (1 byte = 1 letter) and returns the last index of a table (amount of elements in a table)
So it doesn’t actually return the number of items in the table, but returns the index of the last item?
The last index of a table is the amount of elements in a table
if t[i+1] == nil then t[i] is the last index, t being the table and i being the index since you cant go any further
edit: this is the way lua finds how many elements are in a table because how else would it do it