Lua 中 ipairs 与 pairs 功能的自定义实现
iparis
local function myipairs(tbl)
return function(state, control) -- iterator
control = control + 1
local value = tbl[control]
if value == nil then
return nil, nil
end
return control, value
end, nil, 0, nil
end
local tb1 = {2, 3, 4, 5}
for index, value in myipairs(tb1) do
print(index, value)
end
pairs
local function mypairs(tbl)
return function(state, control) -- iterator
control = next(tbl, control)
local value = tbl[control]
return control, value
end, nil, nil, nil
end
local tb = {aa = "bb", 3, 4, 5}
for key, value in mypairs(tb) do
print(key, value)
end