如何在作为字典使用的 Lua 表中“翻页”浏览数据?

如何编写一个函数来遍历一页的数据?最好提供示例代码...

假设我们将一页定义为5个项目。如果我们有一个包含18项的lua表,它需要输出:

  • 第一页:1到5
  • 第二页:6到10
  • 第三页:11到15
  • 第四页:16到18

因此,假设数据类似于:

local data = {}
data["dog"] = {1,2,3}
data["cat"] = {1,2,3}
data["mouse"] = {1,2,3}
data["pig"] = {1,2,3}
.
.
.

如何编写一个函数来执行以下功能:

function printPage (myTable, pageSize, pageNum)
  -- 找到“myTable”中的项目
end

实际上,我甚至不确定作为字典使用的Lua表是否能够实现这一点?在这样的表中没有特定的排序,因此当您返回打印第2页时,如何确保顺序相同?

原文链接 https://stackoverflow.com/questions/10664742

点赞
stackoverflow用户1175455
stackoverflow用户1175455

next 函数允许你按顺序(尽管是不可预测的顺序)遍历一个表。比如:

data = { dog = "Ralf", cat = "Tiddles", fish = "Joey", tortoise = "Fred" }

function printPage(t, size, start)
    local i = 0
    local nextKey, nextVal = start
    while i < size and nextKey ~= nil do
        nextKey, nextVal = next(t, nextKey)
        print(nextKey .. " = " .. nextVal)
        i = i + 1
    end
    return nextKey
end

local nextPage = printPage(data, 2)  -- 打印第一页
printPage(data, 2, nextPage)         -- 打印第二页

我知道这个不完全符合你想要的形式,但我相信它可以很容易地适应。

next 函数返回表中提供的键之后的键以及它的值。当到达表的末尾时,它返回 nil。如果你将第二个参数设为 nil,它将返回表中的第一个键和值。它也已经在 Corona 的文档 中记录,尽管它似乎是相同的。

2012-05-19 11:49:46