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)
table.getn(t)it I'd bad practice, please use#t