在lua中,数组子元素

时间:2016-10-01 02:56:38

标签: arrays lua lua-table

在Lua, 我想选择数组的部分。 以下示例从第二个元素中选择

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

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

在python中[1:]有效。 Lua有类似的语法吗?

1 个答案:

答案 0 :(得分:4)

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)