# Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

# Lua

##### New Coder
i have an easy question, i don't understand why this works:

Code:
``````local fact
fact= function (n)
if n == 0 then return 1
else return n*fact(n-1)
end
end

print(fact(4))``````

and this one not:

Code:
``````local fact = function (n)
if n == 0 then return 1
else return n*fact(n-1)
end
end

print(fact(4))``````

i don't understand the difference, why declaring it first make it works? If i remove the local they both works as expected

Solution

I've found the example from the PIL manual you're talking about here.

I've found this statement within it that may possibly explain why the first works and the second doesn't:
When Lua compiles the call fact(n-1), in the function body, the local fact is not yet defined. Therefore, that expression calls a global fact, not the local one. To solve that problem, we must first define the local variable and then define the function: ...

To sum up: when you make the function call, fact(n-1) is called in the function body, but it can't find the local fact because the interpreter does not believe it's been defined. So, the interpreter attempts to find a global fact and the...

I've found the example from the PIL manual you're talking about here.

I've found this statement within it that may possibly explain why the first works and the second doesn't:
When Lua compiles the call fact(n-1), in the function body, the local fact is not yet defined. Therefore, that expression calls a global fact, not the local one. To solve that problem, we must first define the local variable and then define the function: ...

To sum up: when you make the function call, fact(n-1) is called in the function body, but it can't find the local fact because the interpreter does not believe it's been defined. So, the interpreter attempts to find a global fact and the program encounters a bug because there is no global fact and we get the following error: `lua: file.lua:5: global 'fact' is not callable (a nil value): `

I hope that explains it. If you'd like to read further into it, use the link I gave you above as that will better explain it alongside the examples.

ok, thanks, i understand now.