AlexStack
AlexStack

Reputation: 17401

What happens to local variables in this recursive call?

In a complicated code, I found a weird behavior: apparently Lua doesn't treat local variables the same as C and Java (I'm not surprised but I don't know HOW it treats them anyway!)

I read PIL and Lua-users.org but none doesn't mention what happens to local variables in recursion. It caused me to develop the following test code:

function addN(n)
    local ret=""
    if n>0 then
        ret=ret..addN(n-1)
        print("for n="..n.." ret='"..ret.."'")
    else
        print("n reached 0")
    end
    return ret
end

print("Final result='"..addN(9).."'")

Expected result:

Final result='987654321'

But I get:

Final result=''

Why? How can I reach the expected result?

Upvotes: 1

Views: 348

Answers (1)

cnicutar
cnicutar

Reputation: 182664

You are not actually concatenating n anywhere. Try something like:

ret = tostring(n)..addN(n-1)

Upvotes: 5

Related Questions