I’m writing a very simple program in Lua to learn more about genetic programming. Below is a mutate function to go to a numbered node (nodeNum) in the tree (pop) and either : swap add with sub (or vice-versa) or replace the node with a random number 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
My problem is with count. Calling this function is awkward, since count has to be reset each time :
-- mutate the first 3 elements in program tree t
mutate(t,1)
count = 0
mutate(t, 2)
count = 0
mutate(t, 3)
I’ve tried variations using do ... end like :
do
local count
function mutate(pop, nodeNum)
if not count then
count = 0
...
end
I’ve also tried giving mutate an extra argument mutate(pop, nodeNum, count) and calling it with mutate(t, 1, 0) but I can’t get either method to work correctly.
I may be missing something really obvious, can anyone see a more elegant solution?
1 Answer