Lua如何访问嵌套表中的特定数据

我从CSV文件解析了一些数据到Lua表中。

假设表格像这样,但是更大

tab {
     { id = 1761, anotherID=2, ping=pong}
     { id = 2071, anotherID=4, ping=notpong}
}

现在我想知道每个ID(尚未显示任何其他数据),以将它们存储在另一个表中一段时间。

我现在完全迷失了...

使用你写的,我把它重新写了一遍,然后去看:

minitab = {}
        for i, value in ipairs(tab) do
            local id = value.id
            local anotherID = value.anotherID
            minitab[id] = anotherID
        end

那能行吗?实际上,我后来只想获取一个更大的数组中的2个值(大约30个数据) - 但我只能推送单个数组到GUI下拉列表中。我想将ID保存为键,将“anotherID”值保存为在该键后的文本,以便如果我询问第2071个值,它会显示“名称”4

点赞
用户107090
用户107090

下面的代码将 tab 表中的 id 作为键存储在另一个表中:

id={}
for k,v in ipairs(tab) do
  id[v.id]=true
end

你可以使用 pairs 遍历 id 表来列出 id

如果你想记住每个 id 的来源,可以在循环中使用 id[v.id]=k

2017-02-15 16:51:13
用户7552968
用户7552968

基于您的问题,您可以使用此代码遍历数据表 “tab”,以获取要用于 GUI 数组的 “minitab”。

—-data
tab = {
  {id = "4204", label = "2", desc = "Roancyme"},
  {id = "5517", label = "9", desc = "Bicktuft"},
  {id = "1035", label = "3", desc = "Pipyalum"},
}

—-temporary table
local minitab = {}
for i, option in ipairs(tab) do
  minitab[option.id] = option.label
end

—-print minitab
print('<select>')
for id, label in pairs(minitab) do
  print(string.format('<option value="%s">%s</option>', id, label)) --> <option value="1035">3</option>
end
print('</select>')
print()

然而,我认为没有必要创建一个临时表来存储这些值,因为您可以轻松遍历原始表“tab”,并直接提取您需要的输出;像这样:

—-print directly from tab
print('<select>')
for i, option in ipairs(tab) do
  print(string.format('<option value="%s">%s</option>', option.id, option.label)) --> <option value="1035">3</option>
end
print('</select>')
print()

除非在显示下拉列表之前需要使用它(例如为“标签”添加一些前缀,按“标签”排序“minitab”等);但您不想打扰原始数据表 “tab” 。在这种情况下,使用临时表是有意义的。

—-format values in temporary table
local minitab = {}
for i, option in ipairs(tab) do
  local minitabID = option.id
  local minitabLabel = string.format('Item %s - %s', option.label, option.desc)
  table.insert(minitab, {id = minitabID, label = minitabLabel})
end

—-sort temporary table
table.sort(minitab, function (o1, o2) return o2.label > o1. label end)

—-print formatted values from temporary table
print('<select>')
for i, option in ipairs(minitab) do
  print(string.format('<option value="%s">%s</option>', option.id, option.label)) --> <option value="4204">Item 2 - Roancyme</option>
end
print('</select>')

注意:请注意哪个表迭代使用“ipairs”,哪个表使用“pairs”。在此处查看完整的代码片段 这里

2017-02-23 20:12:30