在 Lua 中,如何选定数组的子元素

在 Lua 中,我想要选择数组的某些部分。下面的示例选择第二个元素开始的部分。

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

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

在 Python 中可以使用 a[1:]。Lua 中是否有类似的语法?

点赞
用户2505965
用户2505965

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

注意,这是元素从 foobar 的浅复制。


或者,在 Lua 5.2 中,你可以使用 table.packtable.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)
2016-10-01 03:28:55