gpt4 book ai didi

Lua获取表的前N个元素

转载 作者:行者123 更新时间:2023-12-03 23:11:01 25 4
gpt4 key购买 nike

有没有一种方法可以获取表格的前 N ​​个元素?更一般地,给我从位置 P 开始的前 N ​​个元素。

或者我是否必须编写一个函数并使用 pairs 来这样做?

最佳答案

如评论表中所述,默认情况下没有订单。它只是一堆键值对。所以你的请求只对序列有意义。下面是每个建议解决方案的一些细节和示例。

local myTable = {"a", "b", "c", "d", "e", "f", "g", "h"}

local p = 3
local n = 4

选项 1: https://www.lua.org/manual/5.3/manual.html#pdf-table.unpack

table.unpack(list [, i [, j]])

Returns the elements from the given list. This function is equivalent to

return list[i], list[i+1], ···, list[j]

By default, i is 1 and j is #list.


print(table.unpack(myTable, p, p+n-1))

c d e f



选项 2: https://www.lua.org/manual/5.3/manual.html#pdf-table.move

table.move (a1, f, e, t [,a2])

Moves elements from table a1 to table a2, performing the equivalent to the following multiple assignment: a2[t],··· =
a1[f],···,a1[e]
. The default for a2 is a1. The destination range can overlap with the source range. The number of elements to be moved must fit in a Lua integer.

Returns the destination table a2.


local slice = table.move(myTable, p, p+n-1, 1, {})

关于Lua获取表的前N个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57189954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com