Hey There!
So I've written this function to be used in one of my addons. It accepts a bunch of tables, and then returns a table containing all values common to every table passed in.
Now, where I'm confused is that it's seemingly never reaching a point in execution, even though it should be.
Code:
local function tableMerge(...)
if select('#', ...) < 3 then error("tableMerge", "inputs") return end
local toReturn = {}
for i=1, select('#', ...) do
local tab = select(i, ...)
if type(tab) == "table" then --ignore any inputs which aren't tables
if not toReturn[1] then
for j,spellbar in pairs(tab) do -- do it this way so we don't actually do anything to the tables passed in
table.insert(toReturn, spellbar)
print("Adding " .. spellbar)
end
else
for j,v in pairs(toReturn) do -- for everything that's common up to this point in iteration:
print("Testing " .. v)
local found = false
for k,spellbar in pairs(tab) do -- for everything in this new table to check
if v == spellbar then -- if we found that the spellbar exists in this new table, say we found it
found = true
print("Found " .. spellbar)
end
end
if not found then -- if we didn't find this element, then remove it from the common table
print("Removing " .. toReturn[j])
table.remove(toReturn, j)
end
end
end
end
end
return toReturn -- return everything that's common
end
function testMerge()
return tableMerge({1,2,3,4,5,6,7}, "test", {2,4,6}, {})
end
Here's example output of what testMerge dumps:
Dump: value=testMerge()
Adding 1
Adding 2
Adding 3
Adding 4
Adding 5
Adding 6
Adding 7
Testing 1
Removing 1
Testing 3
Removing 3
Testing 5
Removing 5
Testing 7
Removing 7
Testing 2
Removing 2
Testing 6
Removing 6
[1]={
[1] = 4
}
I'm very perplexed because it's never actually finding any common elements, even though it should be (It's not removing 2,4,6 when it reaches the 3rd table)
What's even more perplexing to me is that it's never removing the 4th value, even though it should be as the last table is empty.
I've been trying to debug this for over an hour now and I can't figure out why it's behaving like it is. (setting the last table to 2 causes the output to be {2,6}
Any help you guys can give me I would be VERY appreciative!
-Brusalk