Search code examples
lua

Does lua have something like python's slice


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


Solution

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