2

为什么工厂函数不能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
4

2 回答 2

2

工厂/迭代器功能正确实现。问题是,通过使用

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

相当于:

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

iter是一个fromto无法访问的局部变量。删除local,它将运行。

于 2015-07-11T04:26:44.743 回答
2

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

local function fromto(from,to)
    --parameter:invariant state, control variable
    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-11T20:13:14.097 回答