Hi
I habe a problem with recursion in codea. The problem is that local variables in a function are change from an other function!! In other languages this does not happen.
Please see my example program. You can see that a variable “localvar” is changes from a recursive call!!
What can i do make this not happen?
Regards
Franz
Here is the code:
-- recusion test
iter=0
-- Use this function to perform your initial setup
function setup()
print("Hello World!")
end
function recursion(n)
localvar=n
iter = iter + 1
if iter>1 then
print("i am in recursion")
else
print("iter ",iter)
print("localvar ",localvar)
copy=localvar
recursion(2)
print("localvar ",localvar)
if copy~=localvar then print("this is a problem! this should not happen!") end
end
end
-- This function gets called once every frame
function draw()
-- This sets a dark background color
background(40, 40, 50)
-- This sets the line thickness
strokeWidth(5)
print("start test")
recursion(1)
print("end test")
-- Do your drawing here
end
Sorry i was too stupid to post the code, here is the correct version
-- recusion test
iter=0
-- Use this function to perform your initial setup
function setup()
print("Hello World!")
end
function recursion(n)
localvar=n
iter = iter + 1
if iter>1 then
print("i am in recursion")
else
print("iter ",iter)
print("localvar ",localvar)
copy=localvar
recursion(2)
print("localvar ",localvar)
if copy~=localvar then print("this is a problem! this should not happen!") end
end
end
-- This function gets called once every frame
function draw()
-- This sets a dark background color
background(40, 40, 50)
-- This sets the line thickness
strokeWidth(5)
print("start test")
recursion(1)
print("end test")
-- Do your drawing here
end
Recursion does work, the issue is that all variables are global unless you declare them as local. So adding a local in front of copy and localvar make the recursion work… except… you are using the global iter to count depth (naughty naughty). Here’s some code:
-- recusion test
iter=0
-- Use this function to perform your initial setup
function setup()
print("Hello World!")
end
function recursion(n)
local localvar=n
--iter = iter + 1
if localvar>5 then
print("i have hit the bottom")
else
--print("iter ",iter)
print("localvar on the way down",localvar)
local copy=localvar
recursion(localvar + 1)
print("localvar coming back up",localvar)
if copy~=localvar then print("this is a problem! this should not happen!") end
end
end
-- This function gets called once every frame
function draw()
-- This sets a dark background color
background(40, 40, 50)
-- This sets the line thickness
strokeWidth(5)
print("start test")
recursion(1)
print("end test")
-- Do your drawing here
end
Thank you that solves the problem!