Scheduled Maintenance
The wiki will be going down for routine maintenance on Friday, October 4th, 2024, at approximately 3:30 PM Central Time (15:30) or 1:30 PM Pacific Time. The site may be inaccessible during this time and the database will be locked from editing. We expect the maintenance to take about thirty minutes. We strongly encourage joining our Discord for updates.
Module:Parameters/remove holes: Difference between revisions
Jump to navigation
Jump to search
(optimize by checking whether we need to compress before copying; also be more careful with false vs. nil) |
m (1 revision imported) |
(No difference)
|
Latest revision as of 02:19, 10 June 2024
Documentation for this module may be created at Module:Parameters/remove holes/doc
-- A helper function that removes empty numeric indexes in a table,
-- so that the values are tightly packed like in a normal Lua table.
-- equivalent to require("Module:table").compressSparseArray
return function(t)
local highest = 0
for num, _ in pairs(t) do
if type(num) == "number" and num > 0 and num < math.huge and math.floor(num) == num then
highest = math.max(highest, num)
end
end
local need_to_compress = false
for i = 1, highest do
if t[i] == nil then
need_to_compress = true
break
end
end
if not need_to_compress then
-- The previous algorithm always copied, which implicitly removed 'maxindex' (and other non-numeric keys).
-- Some code calls next(val) to check for a value being present, which depends on 'maxindex' not being present,
-- so remove it.
t.maxindex = nil
return t
else
local ret = {}
local index = 1
for i = 1, highest do
if t[i] ~= nil then
ret[index] = t[i]
index = index + 1
end
end
return ret
end
end