Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why lua table.remove with null index still works

Tags:

lua

lua-table

I am seeing the behavior in Lua code that uses table.remove() which removes the last element when I am passing nil in place of the index . It was counter-intuitive to me.

> local tbl = {"this","is","a","list"}
  table.remove(tbl,nil)

will result in the last element deleted from list

> for k,v in ipairs(tbl) do 
     print(k,v)
  end
1       this
2       is
3       a

is there a specific reason for this behavior ?

like image 670
Jabir Ali Avatar asked Mar 13 '26 14:03

Jabir Ali


1 Answers

is there a specific reason for this behavior ?

Yes. table.remove and table.insert are most often used as "push" and "pop" equivalents to remove or add elements at the end of a Lua table, treating it as a "stack". Explicitly providing an index is in fact the "rarer" case (and should be, since it has worst-case linear time due to needing to shift items, whereas just pushing/popping at the end is amortized constant time).

Essentially, you can view this as a sanely handled edge case, which turns out to be the common case. Passing nil or "none" makes Lua take the "default value" of #tbl as index.

table.remove(tbl) and table.remove(tbl, nil) are not the same; one passes "none" (out of stack bounds) as index, the other passes an explicit nil. Lua can distinguish these (and some library functions do), but it would be confusing to programmers - who usually expect nil and "none" to be treated the same - if it did.

If you're not comfortable with using the statement table.remove(tbl) to remove the last element, you might as well set it to nil, which is equivalent: tbl[#tbl] = nil (except table.remove will return the removed element for convenience, but this only matters in expressions).

Similarly, the statement table.insert(tbl, x) is equivalent to tbl[#tbl + 1] = x. Note in particular that for x = nil, table.insert is a no-op (this is often considered a footgun).

like image 142
LMD Avatar answered Mar 15 '26 19:03

LMD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!