如何按确切顺序遍历表? [英] How to iterate through a table in its exact order?
问题描述
如果我尝试输出这个表,它们会以错误的顺序循环:
If i try to output this table, they are looped through in the false order:
local letters = {DIN1="hi", AIN1= "my", AIN2 ="name", DIN2="is"}
for name, value in pairs(letters) do
print(name,value)
end
预期输出:
DIN1 hi
AIN1 my
AIN2 name
DIN2 is
输出:
AIN1 my
DIN2 is
DIN1 hi
AIN2 name
我该如何编码以便 for 循环遍历表格的实际顺序?(定义顺序)
How can i code it so that the for loop runs through the tables actual order? (The order how it was defined)
我不需要字母顺序,但与表定义中的顺序相同.
I don't need the alphabetic order, but the same order as in the definition of the table.
我需要打印密钥和值.在答案Lua 成对与编写的顺序相同"中,只会打印索引号和值
I need to have the key AND the value printed. In the answer "Lua in pairs with same order as it's written" there will be only indexnumber and value printed
推荐答案
你可以利用表的整数部分按顺序存储键:
You may utilize integer part of the table to store keys in order:
function add(t, k, v, ...)
if k ~= nil then
t[k] = v
t[#t+1] = k
return add(t, ...)
end
return t
end
t = add({ }, "A", "hi", "B", "my", "C", "name", "D", "is")
for i,k in ipairs(t) do
local v = t[k]
print(k, v)
end
当然,这假设除了 add
之外的任何东西都不使用整数键.
Of course, this assumes that integer keys are not used by anything except add
.
insert(t, k, v)
和 remove(t, k)
作为练习留给读者.
insert(t, k, v)
and remove(t, k)
left as an exercise to the reader.
add
函数中的省略号(点)允许根据需要传递尽可能多的参数来一次设置多个 kv 对.没有它,我们每次调用只能设置一对,例如 add(t, "A", "hi")
.函数定义 add(t, k, v, ...)
将前三个参数分配给 t, k, v
并保留其他参数不变.然后 add
处理第一对 (t[k]=v
) 并使用其余的 ...
参数递归.
Ellipsis (dots) in add
function allow passing as many arguments as needed to set many kv-pairs at once. Without that, we would be only able to set one pair per call, like add(t, "A", "hi")
. Function definition add(t, k, v, ...)
assigns first three arguments to t, k, v
and leaves others untouched. Then add
processes first pair (t[k]=v
) and recurses with the rest ...
of arguments.
t k v ...
level 1: (t, "A", "hi", "B", "my", "C", "name", "D", "is")
level 2: (t, <- "B", "my", "C", "name", "D", "is")
level 3: (t, <- "C", "name", "D", "is")
level 4: (t, <- "D", "is")
level 5: (t, <- )
在第 5 级,k
和 v
取 nil
s,因为参数列表太短,递归停止.
At level 5, k
and v
take nil
s, because argument list is too short, and recursion stops.
这篇关于如何按确切顺序遍历表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!