Skip to content

Instantly share code, notes, and snippets.

@LPGhatguy
Created June 12, 2018 18:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LPGhatguy/6cf84c7511b40fba6fc08e3da127b307 to your computer and use it in GitHub Desktop.
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.
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