1. pairs 迭代器:
pairs 用于迭代表中所有的键值对,包括字符串键和数字键。示例:
local myTable = {a = 10, b = 20, c = 30}
for key, value in pairs(myTable) do
print(key, value)
end
输出:
local myTable = {a = 10, b = 20, c = 30}
for key, value in pairs(myTable) do
print(key, value)
end
local myArray = {10, 20, 30}
for index, value in ipairs(myArray) do
print(index, value)
end
local function customIterator(t)
local index = 0
return function()
index = index + 1
return t[index]
end
end
local myArray = {10, 20, 30}
local iterate = customIterator(myArray)
while true do
local value = iterate()
if not value then
break
end
print(value)
end