I wrote this function to separate a table into its numerically-indexed and hash-table components:
function separateNumericallyIndexedAndHashTablesIn(thisTable)
local numericalTable, hashTable = {}, {}
for k, v in pairs(thisTable) do
print(k, v)
if type(k) == "number" then
numericalTable[k] = v
else
hashTable[k] = v
end
end
return numericalTable, hashTable
end
And I wrote this code in CodeaUnit to test it (I’m including the print statements I used to debug it);
_:test("separateNumericallyIndexedAndHashTablesIn(...) returns correct tables", function()
--create result flags
local totalResult, numericalCountRight, numericalResult, hashCountRight, hashResult
--make test table and verification tables to check results against
local tableForKey = {}
local testTable = {[1] = "one", [2] = "two", [4] = "four", [10] = "ten",
["red"] = "foo1", ["five"] = "foo2", [tableForKey] = "foo3"}
local correctNumericals = {[1] = "one", [2] = "two", [4] = "four", [10] = "ten"}
local correctHash = {["red"] = "foo1", ["five"] = "foo2", [tableForKey] = "foo3"}
--run the function
local returnedNumericals, returnedHash = separateNumericallyIndexedAndHashTablesIn(testTable)
--inspect counts
local numericalCounter = 0
for i, v in pairs(returnedNumericals) do
numericalCounter = numericalCounter + 1
end
numericalCountRight = numericalCounter == 4
print(table.unpack(correctNumericals))
print(table.unpack(returnedNumericals))
local hashCounter = 0
for i, v in pairs(returnedHash) do
hashCounter = hashCounter + 1
end
hashCountRight = hashCounter == 3
--inspect contents
if numericalCountRight and hashCountRight then
numericalResult = true
hashResult = true
for i, v in pairs(correctNumericals) do
if v ~= returnedNumericals[i] then numericalResult = false end
end
for i, v in pairs(correctHash) do
if v ~= returnedHash[i] then hashResult = false end
end
end
--overall result is AND combination of all results
print(numericalCountRight, numericalResult, hashCountRight, hashResult)
totalResult = numericalCountRight and numericalResult and hashCountRight and hashResult
_:expect(totalResult).is(true)
end)
…does this look right? Are there any cases you think this would miss?