Silly question, but how would I loop through this table in the same order it was written in?
local table1 = {
[1] = {Name = "bla"},
[2] = {Name = "bla2"},
[3] = {Name = "bla3"}
}
Silly question, but how would I loop through this table in the same order it was written in?
local table1 = {
[1] = {Name = "bla"},
[2] = {Name = "bla2"},
[3] = {Name = "bla3"}
}
Use a for index, key in ipairs() loop
a = {"one", "two", "three"}
for i, v in ipairs(a) do
print(i, v)
end
Result:
1 one
2 two
3 three
With pairs():
a = {"one", "two", "three"}
for i, v in pairs(a) do
print(i, v)
end
Result:
1 one
2 three
3 two
To be more precise
I donât know if it would work or not but maybe a function or a while true do loop? Just thinking on the top of my mind.
If itâs just a numerical index generated by table.insert
or you donât manually enter a number that doesnât follow the order of a +1 index then you could use.
for i = 1, #table1 do
print(table1[i].Name)
end
or for i,v in ipairs/pairs recommended by Xx1Luffy1xX
You would use ipairs
as mentioned along as itâs an array otherwise that specific iterator will skip over non-numerical indexes :
for _,v in ipairs(table1) do
print(v.Name) --->> bla, bla2, bla3
end
Or a for loop:
for i =1 , #table1 do
print(table1[i].Name) --->> bla, bla2, bla3
end
for a dictionary however, if you were wondering, which are usually in arbitrary order btw, you would need to order them when new indexes are added to the table , which means using a custom iterator you could do something like:
local T = function(t,...)
for i, v in ipairs(t)do
if typeof(v) == "table" then
t[i] = {next(v)}
end
end
setmetatable(t,t)
t. __newindex = function(Table, index, value)
rawset(Table, #Table + 1, {index, value})
end
return t
end
local function OrderedPairs(t)
local i = 0
return function()
i = i + 1
if t[i] then
if typeof(t[i]) == "number" then
return i, t[i]
end
return t[i][1] or i , t[i][2] or t[i]
end
end
end
local Table = T{ {test123 = 2} } -- values have to be defined in tables when using non-numerical indexes on table creation
table.insert(Table, "Val1")
Table["Foo"] = "bar"
Table["Test1"] = 10
for _,v in OrderedPairs(Table) do
print(_, v) --- >>>> test123 : 2, 1 : Val1 , Foo: bar, Test1 : 10
end
You can simply use a numerical loop such as the following
local table1 = {
[1] = {Name = "bla"},
[2] = {Name = "bla2"},
[3] = {Name = "bla3"}
}
for i = 1, #table1 do
local currentInteration = table1[i]
end
As others have stated above, numerical for loop is the way to go for this.
Pairs doesnât guarantee order.
Not sure if youâre agreeing with me but i clearly stated how pairs() didnât guarantee order,
The title clearly says âin orderâ , but my bad, didnât read that part where you said that.
Yeah I probably shouldnât have included that. However many people confuse ipairs with pairs and it was a great way to show one of the differences between the two
I assume this is just a typo, but the index of 3 still has the value âthreeâ associated with it.