Lua笔记(23)—— pairs和ipairs


pairs() returns an iterator that will return the key and value of every key in the table, in no particular order. Usually, k and v are used to hold the key and value it returns. This is used to perform actions on each item in a table in turn, like when printing the contents of each value in the table.

ipairs() is very similar to pairs(), except that it will start at table[1] and iterate through all numerically indexed entries until the first nil value. It does this in order, which can be useful when you’re looking for the first item in a list that meets certain criterion.



t = {hello = 100, 200, 300}

print("k, v in pairs:")
for k, v in pairs(t) do
    print(k, v)

print("k, v in ipairs:")
for k, v in ipairs(t) do
    print(k, v)


k, v in pairs:
1   200
2   300
hello   100
k, v in ipairs:
1   200
2   300




电子邮件地址不会被公开。 必填项已用*标注

This site uses Akismet to reduce spam. Learn how your comment data is processed.