Does lua have something like python's slice

By creating a new table using the result of table.unpack (unpack before Lua 5.2):

for key, value in pairs({table.unpack({1, 2, 3, 4, 5}, 2, 4)}) do
    print(key, value)
end

This generates...

1   2
2   3
3   4

(Tested in Lua 5.3.4 and Lua 5.1.5.)


There's no syntax sugar for doing this, so your best bet would be doing it via a function:

function table.slice(tbl, first, last, step)
  local sliced = {}

  for i = first or 1, last or #tbl, step or 1 do
    sliced[#sliced+1] = tbl[i]
  end

  return sliced
end

local a = {1, 2, 3, 4}
local b = table.slice(a, 2, 3)
print(a[1], a[2], a[3], a[4])
print(b[1], b[2], b[3], b[4])

Keep in mind that I haven't tested this function, but it's more or less what it should look like without checking input.

Edit: I ran it at ideone.


xlua package has table.splice function. (luarocks install xlua)

yourTable = {1,2,3,4}
startIndex = 1; length = 3
removed_items, remainder_items = table.splice(yourTable, startIndex, length)
print(removed_items) -- 4
print(remainder_items) -- 1,2,3

see: https://github.com/torch/xlua/blob/master/init.lua#L640

Tags:

Lua