Lua 没有类似的语法。但是,您可以定义自己的函数来轻松包装此逻辑。
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
请注意,这是foo 到bar 中元素的浅 副本。
或者,在 Lua 5.2 中,您可以使用 table.pack 和 table.unpack。
local foo = { 1, 2, 3, 4, 5 }
local bar = table.pack(table.unpack(foo, 2, 4))
虽然说明书上是这么说的:
table.pack (···)
返回一个新表,其中所有参数都存储在键 1、2 等中,并带有一个包含参数总数的字段“n”。请注意,结果表可能不是序列。
虽然 Lua 5.3 有 table.move:
local foo = { 1, 2, 3, 4, 5 }
local bar = table.move(foo, 2, 4, 1, {})
最后,大多数人可能会选择在此之上定义某种 OOP 抽象。
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)