跳到主要内容

25、Lua 学习笔记之三(高阶话题)

高阶话题

1.迭代

1、1 实例代码:

--迭代
local function enum(array)
    local index = 1
    return function()
        local ret = array[index]
        index = index + 1
        return ret
    end
end

local function foreach(array,action)
    for element in enum(array)do
        action(element)
    end
end

foreach({1,2,3},print)

输出结果:

1

2

3

1、2 有关迭代的描述:

  • 定义

迭代是for语句的一种特殊形式,可以通过for语句驱动迭代函数对一个给定集合进行遍历。正式、完备的语法说明较复杂,请参考Lua手册。

  • 实现

如前面代码所示:enum函数返回一个匿名的迭代函数,for语句每次调用该迭代函数都得到一个值(通过element变量引用),若该值为nil,则for循环结束。

2.协作线程

2、1 实例代码

--线程
local function producer()
    return coroutine.create(
    function(salt)
        local t = {1,2,3}
        for i = 1,#t do
            salt = coroutine.yield(t[i] + salt)
        end
    end
    )
end

function consumer(prod)
    local salt = 10
    while true do
        local running ,product = coroutine.resume(prod, salt)
        salt = salt*salt
        if running then
            print(product or "END!")
        else
            break
        end
    end
end

consumer(producer())

输出结果:

11

102

10003

END!

2、2 有关协作线程的描述:

  • 创建协作线程

通过coroutine.create可以创建一个协作线程,该函数接收一个函数类型的参数作为线程的执行体,返回一个线程对象。

  • 启动线程

通过coroutine.resume可以启动一个线程或者继续一个挂起的线程。该函数接收一个线程对象以及其他需要传递给该线程的参数。线程可以通过线程函数的参数或者coroutine.yield调用的返回值来获取这些参数。当线程初次执行时,resume传递的参数通过线程函数的参数传递给线程,线程从线程函数开始执行;当线程由挂起转为执行时,resume传递的参数以yield调用返回值的形式传递给线程,线程从yield调用后继续执行

  • 线程放弃调度

线程调用coroutine.yield暂停自己的执行,并把执行权返回给启动/继续它的线程;线程还可利用yield返回一些值给后者,这些值以resume调用的返回值的形式返回。

参考文献《C/C++程序员的Lua快速入门》