lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Remember that function arguments are evaluated before applying the function to them. What this construction does is that it first unpacks the removed elements, pushing them on the stack; this is then passed as an argument to a function to avoid having to store them in a table or the like. The function then calls table.move and returns the removed elements afterwards. In the end this is a clever trick to "store" a vararg on the stack.

The table.move line is correct. It is equivalent to the following assignments:

list[pos], list[pos + 1], ..., list[pos + count - 1] = list[pos + count], list[pos + count + 1], ..., list[#list + count]

Does this extend beyond the length of the table? Yes, because it must: The new table length must be shorter; therefore, the last count elements must be nil. That's exactly what using #list + count as upper limit achieves.

Using your line, the last count elements would be duplicated, with one occurrence starting at the position where they were deleted, and the second occurrence right after that until the end of the list.

On 11.09.22 08:38, bil til wrote:
How smart looks this Egor ... :).

... but if I am not completely stupid, this "table.move..." line is
not quite correct, it should better be:
table.move(list, pos + count, #list, pos)

???

And can you give me a hint, by which miraculous trick this bizarre
return construction should return the removed elements?

(generally I think in an interpreter language as Lua, it is always a
very good idea, to support any user in avoiding for loops for "common
tasks". I think this are only some small amount of C lines more to
program this, but Luiz of course is completely reasonable to ask for
some C code proposal for this... then much more easy to discuss "C
code weight" against "Lua code advantage".

Am Sa., 10. Sept. 2022 um 23:09 Uhr schrieb Egor Skriptunoff
<egor.skriptunoff@gmail.com>:
   return
      (
         function (...)
            table.move(list, pos + count, #list + count, pos)
            return ...
         end
      )
      (
         table.unpack(list, pos, pos + count - 1)
      )
end