Recursion 在递归Lua函数中重置变量
我正在用Lua编写一个非常简单的程序来学习更多关于遗传编程的知识。下面是一个变异函数,用于转到树(Recursion 在递归Lua函数中重置变量,recursion,lua,scope,Recursion,Lua,Scope,我正在用Lua编写一个非常简单的程序来学习更多关于遗传编程的知识。下面是一个变异函数,用于转到树(pop)中的编号节点(nodeNum),或者:用sub替换add(反之亦然),或者用随机数1-100替换节点 local count = 0 function mutate(pop, nodeNum) for k,v in ipairs(pop) do if type(v) == "table" then mutate(v, nodeNum)
pop
)中的编号节点(nodeNum
),或者:用sub替换add(反之亦然),或者用随机数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
:
-- mutate the first 3 elements in program tree t
mutate(t,1)
count = 0
mutate(t, 2)
count = 0
mutate(t, 3)
我尝试过使用do。。。结束
类似于:
do
local count
function mutate(pop, nodeNum)
if not count then
count = 0
...
end
我还尝试给mutate一个额外的参数mutate(pop,nodeNum,count)
,并用mutate(t,1,0)
调用它,但我无法让这两种方法都正常工作
我可能遗漏了一些非常明显的东西,有人能看到一个更优雅的解决方案吗?我实际上不使用Lua,但是,最简单的方法不是可能是创建另一个调用此函数的函数,该函数在当前方法返回后将count设置为零吗?例:
function mutateExample(pop, nodeNum)
mutate(pop, nodeNum)
count = 0;
end
这样,mutate就可以递归地调用它自己,然后一旦完成,count就会被重置。count必须是函数内部的局部变量,而不是函数外部的局部变量。它是一个堆栈变量,因此将其放入函数的堆栈中:
function mutate(pop, nodeNum)
local count = 0
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
如果希望多个函数调用共享变量,则只能使用外部
local
变量。此解决方案在每次递归调用函数时重置count
,但我需要的是一个静态变量,它仅在函数完成递归时重置。非常简单。它甚至在Lua的编程中!
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