Hello everyone.
I have been working on this for the past half hour, as it got a bit annoying that I had to keep on make 3-4 loops in a lot of my functions. So, the solution for this? a custom iterator, which accept inputs of several tables to iterate through at once!
What do I mean by this?
Well, take a look at this:
local t1 = {1, 3, 5}
local t2 = {2, 4, 6}
for i1, v1, i2, v2 in CombinedPairs(t1, t2) do
print(i1, v1, '|', i2, v2)
end
Expected output:
I hope you can already see the usecases for this
When it comes to dictionaries, the order is undefined due to the nature of tables. Beware!
The code for this is (pretty) basic: it simply iterates through all the tables you input to it, returning the key | value pair of each table, and then combining the pairs of every table and returning those.
The code is really small, and as such there’s no need to upload it anywhere.
You can just grab the source code directly from here:
Click me for the source
function CombinedPairs(...)
local Tables = {...}
for Idx, Obj in next, Tables do
assert(type(Obj) == 'table', 'Bad argument #' .. Idx .. ' (table expected, got ' .. typeof(Obj) .. ')')
end
local NumInput = #Tables
local Idx = nil
local Working = table.create(NumInput, true)
return function()
local Returns = {}
local IsEmpty = true
for TableIdx, Table in next, Tables do
if Working[TableIdx] then
local Worked, Val, Key = pcall(next, Table, Idx)
if Worked == false and Key == nil then
Working[TableIdx] = false
continue
end
IsEmpty = false
Returns[#Returns + 1] = Val
Returns[#Returns + 1] = Key
end
end
if IsEmpty then
return
end
Idx = Idx and Idx + 1 or 1
return unpack(Returns)
end
end
Example usage:
local t1 = {1, 3, 5}
local t2 = {2, 4, 6}
for i1, v1, i2, v2 in CombinedPairs(t1, t2) do
print(i1, v1, '|', i2, v2)
end
Enjoy! hopefully this turns out useful for anyone