Re: table.remove not shifting keys when Lua file is in bytecode format

  • From: Egor Skriptunoff <egor.skriptunoff@xxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Tue, 25 May 2021 04:37:23 +0300

On Fri, May 21, 2021 at 5:19 PM Demi Marie Obenour wrote:

table.remove() calculates the length of the table to determine
how much to move.
Avoid nil in arrays.

Would it be possible to issue a warning when this happens?



You can redefine table.remove() and some other functions to raise an
exception if there is a nil inside.

function must_have_no_nils_inside(t)
   local len, ctr, outside = #t, 0
   for k in pairs(t) do
      if type(k) == "number" and k > 0 and k % 1 == 0 then
         ctr, outside = ctr + 1, outside or k > len
      end
   end
   if outside or ctr ~= len then
      error("Array contains nil inside", 3)
   end
end

function table.check_and_remove(t, ...)
   must_have_no_nils_inside(t)
   return table.remove(t, ...)
end

local x = {11, 22}
table.check_and_remove(x)  -- ok
x = {nil, 22}
table.check_and_remove(x)  -- error

Other related posts: