Reputation: 231
I'm trying to write a lua
function in which I pass two rectangles coordinates and receive the values on polar coordinates. Somehow the code I wrote returns an error and I can't see where I went wrong. How do I fix it?
io.write("Enter first coord: ")
F = io.read()
io.write("Enter second coord: ")
S = io.read()
A = tonumber(F)
T = tonumber(S)
getPolar(A,T)
function getPolar(x,y)
mag = math.sqrt(x^2+y^2)
ang = math.atan(y/x)
return print("Magnitude: " .. tostring(mag) .. " Angle: " .. tostring(ang))
end
The error I receive is the following:
Polar.lua:9: attempt to call a nil value (global 'getPolar') stack traceback: Polar.lua:9: in main chunk [C]: in ?
Upvotes: 1
Views: 392
Reputation: 28950
Lua is interpreted line by line.
You're calling getPolar
befor you define it.
Move to function call behind the function definition to fix that.
Please note that print
does not return a value so you can omit the return
in your function.
You should use local variables wherever you can. It would make sense to restrict the scope of mag
and ang
to your function body.
Use math.atan2
to calculate the angle as it will handle the quadrants correctly.
See https://de.wikipedia.org/wiki/Arctan2
function getPolar(x,y)
local mag = math.sqrt(x^2+y^2)
local ang = math.atan2(x,y)
return mag, ang
end
local mag, ang = getPolar(A,T)
print("Magnitude: " .. tostring(mag) .. " Angle: " .. tostring(ang))
Upvotes: 2