lua __pairs元方法(一)
__pairs元方法的介绍
__pairs元方法的作用
__pairs元方法用于自定义循环一个对象时的行为。
当我们使用in结构来迭代一个对象时,实际上是调用该对象的__pairs元方法来进行遍历。
__pairs元方法的用法
__pairs元方法必须返回一个迭代器和初始状态参数,迭代器每次返回一个键值对。
使用如下语法定义__pairs元方法:
function myPairs(obj)
    return function (obj, index)
        -- 返回下一个键值对
    end, obj, nil
end
-- 将myPairs方法赋值给自己定义的对象的__pairs字段
myObject.__pairs = myPairs
使用__pairs元方法实现不同类型对象的迭代
lua字符串转数组迭代数组
一个简单的数组可以通过__pairs方法来进行迭代,示例代码如下:
local myArray = {1, 2, 3, 4, 5}
-- 定义myArray的__pairs元方法
function myArray.__pairs()
    local index = 0
    return function (array, index)
        index = index + 1
        if array[index] ~= nil then
            return index, array[index]
        end
    end, myArray, index
end
-- 使用for循环遍历数组
for index, value in pairs(myArray) do
    print(index, value)
end
输出结果:
1  1
2  2
3  3
4  4
5  5
迭代自定义对象
我们可以通过自定义__pairs元方法来实现对自定义对象的迭代。示例代码如下:
local myObject = {}
-- 定义myObject的__pairs元方法
function myObject.__pairs()
    local index = 0
    return function (object, index)
        index = index + 1
        local key = [index]
        if key ~= nil then
            return key, object[key]
        end
    end, myObject, index
end
= {"name", "age", "gender"}
= "John"
= 25
= "Male"
-- 使用for循环遍历myObject
for key, value in pairs(myObject) do
    print(key, value)
end
输出结果:
name    John
age    25
gender  Male
迭代自定义迭代器对象
我们也可以定义一个迭代器对象,并通过该对象的__pairs元方法来进行迭代。示例代码如下:
-- 创建一个迭代器对象
local function myIterator(collection)
    local index = 0
    local size = #collection
    return function ()
        index = index + 1
        if index <= size then
            return collection[index]
        end
    end
end
local myCollection = {"apple", "banana", "grape"}
-- 定义myCollection的__pairs元方法

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。