local Table = {}
local Current = 1
while true do
if Current == #Table then break end
print(Current, Table[Current])
Current += 1
end
and
local Table = {}
local Current = 1
repeat
print(Current, Table[Current])
Current += 1
until Current == #Table
Why can this be used instead of for? I dont know
Both cases can be used for when you will only use X amount from a table, I don’t know, you want to select 20 objects at random.
local list = {"A", "B", "C", "D", "E", "F"} -- Some table
while #list > 0 do
local elem = table.remove(list, math.random(1, #list))
print(elem)
end
--NOTE: this method will not catch any (key, value) paired elements
--Also, after the while loop the table will be empty
There’s also a couple iterator functions that I think were added a while back. Definitely weren’t available (or at least documented in the wiki) when I was first learning:
local list = {"A", "B", "C", "D", "E", "F"} -- Some table
function doPrint(i, v)
print(i, v)
end
print("--foreach--")
table.foreach(list, doPrint)
print("--foreachi--")
table.foreachi(list, doPrint)
local list = {"A", "B", "C", "D", "E", "F"} -- Some table
while #list > 0 do
local i = math.random(1, #list)
local v = list[i]
table.remove(list, i)
print(i, v)
end
Yes, by (key, value) paired elements I meant tables that had structures similar to:
mixed = {
"A",
"B",
"C" = {1,2,3,4}
}
Technically string element “A” is at index (or key) 1 (mixed[1]); the same goes for string element “B” (mixed[2]), however that while loop would have no idea about the existence of key “C” since it exists at mixed["C"] – and the ‘#’ operator does not include non-array indexed elements in its count.
local Table = {
[3] = 3, -- index = 3, key = 3, value = 3
[2] = 4, -- index = 2, key = 2, value = 4
[1] = true -- index = 1, key = 1, value = true
}
since Studio will always order it.
If there is Index that is not a number, the table will be called Dictionary and index will be called key, although there are many (including myself) that use key for both.