Hi, Lua noob here. Just started today and have this question about functions and return statements. In the following snippet, the value of x is nil, and I cannot understand why. Can someone help?
function squareAndCube (x)
print ("Enter any number to get the square and cube:")
x = io.read()
square = x * x
cube = square * x
print ("The number you entered, its square, and cube are:")
return x, square, cube
end
print (squareAndCube ())
print (x)
print (square)
print (cube)
--------------------- (OUTPUT)------------------
Enter any number to get the square and cube:
5
The number you entered, its square, and cube are:
5 25 125
nil
25
125
Comments
nil because x is defined locally in the function squareAndCube (x), it is only visible in this function.
function squareAndCube (x)
print ("Enter any number to get the square and cube:")
x = io.read()
square = x * x
cube = square * x
xinput = x
print ("The number you entered, its square, and cube are:")
return xinput, square, cube
end
print (squareAndCube ())
print (xinput)
print (square)
print (cube)
-----------------------------
I was also able to solve it just be removing x from the function argument:
function squareAndCube ()
print ("Enter any number to get the square and cube:")
x = io.read()
square = x * x
cube = square * x
print ("The number you entered, its square, and cube are:")
return x, square, cube
end
print (squareAndCube ())
print (x)
print (square)
print (cube)
Thanks again for your help!
---------------------------------
On an unrelated note, how are you getting your code snippets to appear formatted they way you are?
Likes: MoKaLux
I am happy to help
Likes: zamond
Likes: MoKaLux
Likes: zamond, SinisterSoft, MoKaLux