Lua 5.2 table.insert, table.remove gotcha

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view

Lua 5.2 table.insert, table.remove gotcha

Dirk Laurie-2
I've just fallen into this trap: if `T` is a table with a trivial
__len metamethod that simply returns a constant upper bound for the
largest index you may use,  then

    v=table.remove(T,k); table.insert(T,k,v)

restores T to its original state, but

    table.insert(T,k,v); v=table.remove(T,k)

only does so if T[#T] was originally nil.  Reason: table.insert(T,k,v)
moves T[#T] to T[#T+1] where table.remove can't reach it.