2016-10-01 63 views
2

在Lua中, 我想选择数组的各个部分。 [1:]作品 下面的例子从第二元件在lua中,array子元素

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

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

在Python选择。 Lua是否有类似的语法?

+1

请不要使用'''table.getn(t)'''我不习惯,请使用'''#t''' – warspyking

回答

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 

注意,这是在foo的元素bar副本。


另外,在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)