Created
June 12, 2018 18:13
-
-
Save LPGhatguy/6cf84c7511b40fba6fc08e3da127b307 to your computer and use it in GitHub Desktop.
A quick-and-dirty list comparison function in Lua that visualizes each list, handling sparse arrays correctly.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local function compareList(list, len) | |
-- We use varargs here since spare arrays make Lua upset | |
return function(...) | |
len = len or select("#", ...) | |
local hasDifference = false | |
local differentIndexes = {} | |
for i = 1, len do | |
if list[i] ~= select(i, ...) then | |
differentIndexes[i] = true | |
hasDifference = true | |
end | |
end | |
if hasDifference then | |
local expectedList = {} | |
local foundList = {} | |
local expectedDifference = {} | |
local foundDifference = {} | |
for i = 1, len do | |
local expected = tostring((select(i, ...))) | |
local found = tostring(list[i]) | |
local expectedLen = #expected | |
local foundLen = #found | |
if expectedLen > foundLen then | |
found = found .. (" "):rep(expectedLen - foundLen) | |
elseif foundLen > expectedLen then | |
expected = expected .. (" "):rep(foundLen - expectedLen) | |
end | |
table.insert(expectedList, expected) | |
table.insert(foundList, found) | |
if differentIndexes[i] then | |
table.insert(expectedDifference, ("^"):rep(expectedLen) .. (" "):rep(#expected - expectedLen)) | |
table.insert(foundDifference, ("^"):rep(foundLen) .. (" "):rep(#found - foundLen)) | |
else | |
table.insert(expectedDifference, (" "):rep(#expected)) | |
table.insert(foundDifference, (" "):rep(#found)) | |
end | |
end | |
local message = ("Lists were different!\nExpected:\n%s\n%s\nFound:\n%s\n%s"):format( | |
table.concat(expectedList, ", "), | |
table.concat(expectedDifference, " "), | |
table.concat(foundList, ", "), | |
table.concat(foundDifference, " ") | |
) | |
error(message, 2) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment