如何实现Lua无序表的指定顺序打印?
Got it, let's tackle this problem head-on. As you've already figured out, Lua tables don't keep track of a custom order for string keys—they store those entries in a hash table with no inherent sequence. The only way to print in your exact desired order is to explicitly define that sequence yourself, then loop through that predefined list to pull values from your original table.
Here's a straightforward, step-by-step solution:
- Create an ordered key list: Make an array that holds your table's keys in the exact order you want to print them. This acts as your "guide" for traversal.
- Loop through the ordered list: Iterate over this guide array, fetch the corresponding value from your
tableofStufffor each key, then print the pair.
Full Code Example
local tableofStuff = {} tableofStuff['White'] = 15 tableofStuff['Red'] = 55 tableofStuff['Orange'] = 5 -- Quick note: your desired output shows Orange as 4, but your original table sets it to 5. Adjust this value as needed! tableofStuff['Pink'] = 12 -- Define your exact desired print order here local desiredPrintOrder = {'Red', 'White', 'Pink', 'Orange'} -- Iterate through the ordered list to print each key-value pair for _, key in ipairs(desiredPrintOrder) do local value = tableofStuff[key] -- Optional: handle cases where a key might not exist in the table if value then print(string.format("%s, %d", key, value)) else print(string.format("%s: Value not found in table", key)) end end
Why This Works
Lua's hash table entries (like your string-keyed values) have no guaranteed order. By using a separate array to define your sequence, you're overriding Lua's default behavior and forcing the loop to follow your specified order. The ipairs function is ideal here because it reliably iterates over integer-indexed arrays in strict sequential order.
If you ever need to adjust the print order later, you just modify the desiredPrintOrder array—no need to rework the original table itself.
内容的提问来源于stack exchange,提问作者aJynks

