Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does lua have something like python's slice

Tags:

lua

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

like image 927
Samuel Avatar asked Jul 18 '14 08:07

Samuel


3 Answers

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

like image 99
Fantix King Avatar answered Nov 08 '22 09:11

Fantix King


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.

like image 44
Advert Avatar answered Nov 08 '22 10:11

Advert


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

like image 3
EuWern Avatar answered Nov 08 '22 10:11

EuWern