Does lua have something like python's slice
Asked Answered
V

4

28

Like in python I can use slice. Like following

b=[1,2,3,4,5]
a=b[0:3]

Can I do that kind of operation in Lua without a loop. Or Loop is the most efficient way to do that

Violoncello answered 18/7, 2014 at 8:58 Comment(1)
github.com/justincormack/sliceMonomorphic
A
14

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.

Aye answered 18/7, 2014 at 10:56 Comment(1)
There is syntax sugar for this, see the answer from @Fantix KingZoie
V
42

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.)

Vantage answered 9/1, 2018 at 3:52 Comment(0)
A
14

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.

Aye answered 18/7, 2014 at 10:56 Comment(1)
There is syntax sugar for this, see the answer from @Fantix KingZoie
E
3

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

Eulogist answered 4/8, 2017 at 16:53 Comment(0)
G
0

What about ;

function table.slice(tbl, first, N)
  local sliced = {}
  local ix = first
  local last = math.min(ix + N - 1, #tbl)
  while ix <= last do
    sliced[#sliced+1] = tbl[ix]
    ix = ix + 1
  end
  return sliced
end
Girlhood answered 21/4, 2024 at 17:50 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Nitre

© 2022 - 2025 — McMap. All rights reserved.