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是否有類似的語法?
在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是否有類似的語法?
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)
請不要使用'''table.getn(t)'''我不習慣,請使用'''#t''' – warspyking