4

In Lua, I want to select the parts of the array. The below example selects from the second elements

a = { 1, 2, 3}
print(a)

b = {}
for i = 2, table.getn(a) do
  table.insert(b, a[i])
end
print(b)

In python a[1:] works. Does Lua have the similar syntax?

1
  • 1
    Please do not use table.getn(t) it I'd bad practice, please use #t Commented Oct 1, 2016 at 4:38

1 Answer 1

7

Lua does not have similar syntax. However, you can define your own function to easily wrap this logic up.

local function slice (tbl, s, e)
    local pos, new = 1, {}
    
    for i = s, e do
        new[pos] = tbl[i]
        pos = pos + 1
    end
    
    return new
end

local foo = { 1, 2, 3, 4, 5 }
local bar = slice(foo, 2, 4)

for index, value in ipairs(bar) do
    print (index, value)
end

Note that this is a shallow copy of the elements in foo to bar.


Alternatively, in Lua 5.2 you could use table.pack and table.unpack.

local foo = { 1, 2, 3, 4, 5 }
local bar = table.pack(table.unpack(foo, 2, 4))

Although the manual has this to say:

table.pack (···)

Returns a new table with all parameters stored into keys 1, 2, etc. and with a field "n" with the total number of parameters. Note that the resulting table may not be a sequence.


While Lua 5.3 has table.move:

local foo = { 1, 2, 3, 4, 5 }
local bar = table.move(foo, 2, 4, 1, {})

And finally, most would probably opt to define some kind of OOP abstraction over this.

local list = {}
list.__index = list

function list.new (o)
    return setmetatable(o or {}, list)
end

function list:append (v)
    self[#self + 1] = v
end

function list:slice (i, j)
    local ls = list.new()
    
    for i = i or 1, j or #self do
        ls:append(self[i])
    end
    
    return ls
end

local foo = list.new { 1, 2, 3, 4, 5 }
local bar = foo:slice(2, 4)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.