【问题标题】:How can I print a LUA table in order?如何按顺序打印 LUA 表?
【发布时间】:2018-09-05 06:05:51
【问题描述】:

我有一张桌子需要按顺序打印出来。我知道 LUA 表没有订购。但我很难以有序的方式打印出来。我已经从这个网站上剪下了十几个代码片段,但我无法让它工作。

假设我有一张这样的桌子:

local tableofStuff = {}
      tableofStuff['White'] = 15
      tableofStuff['Red'] = 55
      tableofStuff['Orange'] = 5
      tableofStuff['Pink'] = 12

我怎样才能让它像这样打印...

Red, 55
White, 15
Pink, 12
Orange, 4

在循环中使用这样的行...

print(k..', '..v)

【问题讨论】:

标签: sorting printing lua lua-table


【解决方案1】:

您可以将键/值对存储在数组中,按第二个元素对数组进行排序,然后循环遍历该数组。 (这个例子使用了尾递归,因为我就是这么想的。)

local tableofStuff = {}
tableofStuff['White'] = 15
tableofStuff['Red'] = 55
tableofStuff['Orange'] = 5
tableofStuff['Pink'] = 12

-- We need this function for sorting.
local function greater(a, b)
  return a[2] > b[2]
end

-- Populate the array with key,value pairs from hashTable.
local function makePairs(hashTable, array, _k)
  local k, v = next(hashTable, _k)
  if k then
    table.insert(array, {k, v})
    return makePairs(hashTable, array, k)
  end
end

-- Print the pairs from the array.
local function printPairs(array, _i)
  local i = _i or 1
  local pair = array[i]
  if pair then
    local k, v = table.unpack(pair)
    print(k..', '..v)
    return printPairs(array, i + 1)
  end
end

local array = {}
makePairs(tableofStuff, array)
table.sort(array, greater)
printPairs(array)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 2017-10-09
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    相关资源
    最近更新 更多