开发者

What happens to local variables in this recursive call?

开发者 https://www.devze.com 2023-04-07 04:13 出处:网络
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!)

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?


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

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

精彩评论

暂无评论...
验证码 换一张
取 消