recursion - 重置递归 Lua 函数中的变量

标签 recursion lua scope

我正在用 Lua 编写一个非常简单的程序,以了解有关遗传编程的更多信息。下面是一个 mutate 函数,用于转到树中的编号节点 (nodeNum) (pop),并且可以:将 add 与 sub 交换(或反之亦然)或替换节点的随机数为 1-100。

local count = 0
function mutate(pop, nodeNum)
    for k,v in ipairs(pop) do
        if type(v) == "table" then
            mutate(v, nodeNum)
        else
            count = count + 1
        end

        if count == nodeNum and k == 1 then -- correct node
            if type(v) == "function" then
                if v == add then
                    pop[k] = sub
                else
                    pop[k] = add
                end
            else
                pop[k] = math.random(100)
            end
        end
    end
end

我的问题是count。调用这个函数很尴尬,因为每次都必须重置 count :

-- mutate the first 3 elements in program tree t 
mutate(t,1)
count = 0
mutate(t, 2)
count = 0
mutate(t, 3)

我尝试过使用 do ... end 的变体,例如:

do
    local count
    function mutate(pop, nodeNum)
    if not count then
        count = 0
    ...
end

我还尝试给 mutate 一个额外的参数 mutate(pop, nodeNum, count) 并用 mutate(t, 1, 0) 调用它,但我可以这两种方法都无法正常工作。

我可能错过了一些非常明显的东西,有人能看到更优雅的解决方案吗?

最佳答案

function mutate(pop, nodeNum, count)
    count = count or 0

    for k,v in ipairs(pop) do
        if type(v) == "table" then
            mutate(v, nodeNum, count)
        else
            count = count + 1
        end

        if count == nodeNum and k == 1 then -- correct node
            if type(v) == "function" then
                if v == add then
                    pop[k] = sub
                else
                    pop[k] = add
                end
            else
                pop[k] = math.random(100)
            end
        end
    end
end

关于recursion - 重置递归 Lua 函数中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12231855/

相关文章:

class - Lua 错误创建类

lua - lua中的尾调用优化

java - 使用不同的参数运行参数化的 JUnit 测试

javascript - 你能更新一个 Controller 来更新它的子范围吗?

python - 了解 Python 闭包

java - 以最少的运行时间存储带递归的斐波那契数列的值

python - 检查递归中的 2 个字符

lua - Lua中的userdata和lightuserdata是什么?

java - 递归,每一步导出信息

java - 方形子序列