Lua中的工厂函数无法将本地迭代器返回给for循环?

为什么工厂函数 fromto 不能将本地函数 iter 作为迭代器返回给 for 循环?

function fromto(from,to)
    return iter,to,from-1
end

local function iter(to,from)--parameter:invariant state, control variable
    from = from + 1
    if from <= to then
        return from
    else
        return nil
    end
end

for i in fromto(1,10) do
    print(i)
end
点赞
用户1009479
用户1009479

工厂/迭代器函数已经正确地实现了。问题在于,通过使用

local function iter(to,from)
  --...
end

等价于:

local iter = function(to,from)
  --...
end

iter 是一个本地变量,fromto 无法访问。移除 local 即可运行。

2015-07-11 04:26:44
用户2226988
用户2226988

正如 @YuHao 所说,你的方案可以工作。有几种方法可以重新排列你的代码。这是其中一种:

local function fromto(from,to)
    --参数:不变状态,控制变量
    local function iter(to,from)
        from = from + 1
        if from <= to then
            return from
        else
            return nil
        end
    end

    return iter,to,from-1
end

for i in fromto(1,10) do
    print(i)
end

需要理解的两个事情:变量作用域和函数是值。

  1. 变量要么是全局的,要么是局部的。局部变量是按字面上的作用域来定义的。它们的作用域从它们的声明语句后面的语句一直到块的结束。如果一个变量不是局部变量的名称,它就成为全局变量的引用。在你的第2行中,iter 是一个全局变量。

  2. 函数不是声明的,它们是在执行函数定义表达式时创建的值。 (一个函数定义语句只是一个函数定义表达式的另一种语法,用于定义并分配给一个变量。)另外,函数没有名称。它们只是被一个或多个变量引用。所以,你的函数值存在,并且被 iter 变量引用,直到执行控制通过包含函数定义的行。在你的代码中,那是第11行的结尾。

2015-07-11 20:13:14