如何自动索引表并在保留所有数据的同时将其循环到ipairs中?

时间:2014-08-31 06:23:30

标签: loops lua indexing lua-table

表:

localization_strings = {
    string_1 = "Text Here",
    string_2 = "Some More Text Here",
    string_3 = "More Text"
}

这显然不是整张表,只是一个小样本。真正的桌子超过500多行。我不仅重做表的原因是因为其他函数引用它并且我无法访问这些文件来修复它们,所以我必须找到一个解决方法。此外,因为这将是相当繁琐的工作,并可能导致其他代码的问题。

我已经尝试了两次尝试解决这个问题,但我只能得到我想要的一个值(我认为这个术语不正确),我需要两个,因为1是显示文本,1是函数调用的数据。 / p>

尝试:

-- Attempt #1
-- Gives me the string_#'s but not the "Text"...which I need, as I want to display the text via another function
LocalizationUnorderedOpts = {}
LocalizationOpts = {}
for n,unordered_names in pairs(localization_strings) do
    if (unordered_names) then
        table.insert( LocalizationUnorderedOpts, n)
    end
end
io.write(tostring(LocalizationUnorderedOpts) .. "\n")
table.sort(LocalizationUnorderedOpts)

for i,n in ipairs(LocalizationUnorderedOpts) do 
    if (n) then
        io.write(tostring(i))
        table.insert( LocalizationOpts, { text = tostring(LocalizationUnorderedOpts[i]), callback = function_pointer_does_not_matter, data = i } )
    end
end

-- Attempt #2
-- Gives me the "Text" but not the string_#'s...which I need to as data to the callback to another function (via function pointer)
LocalizationUnorderedOpts = {}
LocalizationOpts = {}
for n,unordered_names in pairs(localization_strings) do
    if (unordered_names) then
        table.insert( LocalizationUnorderedOpts, localization_strings[n])
    end
end
io.write(tostring(LocalizationUnorderedOpts) .. "\n")
table.sort(LocalizationUnorderedOpts)

for i,n in ipairs(LocalizationUnorderedOpts) do 
    if (n) then
        io.write(tostring(i))
        table.insert( LocalizationOpts, { text = tostring(LocalizationUnorderedOpts[i]), callback = function_pointer_does_not_matter, data = i } )
    end
end

1 个答案:

答案 0 :(得分:2)

如果我理解正确,您需要对非数组表进行排序。您的第一次尝试完成了大部分工作:构建另一个表,其值与原始表中的键相同。

剩下的是如何获取原始值,如"Text Here",因为您需要索引原始表:

for k, v in ipairs(LocalizationUnorderedOpts) do
    print(v)                       --original key
    print(localization_strings[v]) --original value
end