NIL error

I am reading the Programming in Lua and I am getting a nil error using this code:


  -- defines a factorial function
function fact (n)
    if n == 0 then
        return 1
    else
		return n * fact(n-1)
    end
end
    
print("enter a number:")
a = io.read("*number")        -- read a number
print(fact(a))

And I am getting this error:

http://puu.sh/1YZjV

-snip-

Any help would be appreciated. I thank you for your time because I know the pros can get annoyed when us newbies come and make help threads, but I would appreciate it if you help.

-TheDeadlyHaze :smile:

n isnt defined anywhere. You need [LUA]n = something[/LUA] in there somewhere

I am getting this error now :v

http://puu.sh/1Z3fw

Here’s my code.


n = 2

function fact (n)
    if n == 0 then
        return 1
    else
		return n * fact(n-1)
    end
end
    
print("enter a number:")
a = io.read("*number")        -- read a number
print(fact(a))

It’s the inputted number that’s nil (which is a).
The parameter is n should be inputted in your last line but if a is nil, n will also be.

[lua]if ( n and n == 0 ) then[/lua]

safeguard

or default it to 0.

[lua]local n = n or 0;[/lua] top of the function.