Lua函数不返回值

我正在尝试编写一个lua函数,其中我传递两个矩形坐标并在极坐标上接收值。不知何故,我编写的代码返回错误,我无法看出错误在哪里。我该如何修复?

io.write("输入第一个坐标:")
F = io.read()
io.write("输入第二个坐标: ")
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("大小:" .. tostring(mag) .. " 角度:" .. tostring(ang))
end

我收到的错误如下所示:

Polar.lua:9:尝试调用没有值的nil值(全局' getPolar')堆栈跟踪:> Polar.lua:9:在主块中 C:?

点赞
用户2858170
用户2858170

Lua 是逐行解释的。

你在定义 getPolar 函数之前调用了它。

将函数调用移到函数定义之后即可修复这个问题。

请注意,print 函数不会返回值,因此你可以在函数中省略 return

尽可能使用本地变量,将 magang 的作用域限制在函数体内比较合理。

使用 math.atan2 计算角度,它可以正确地处理不同象限。详见 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))
2019-12-11 12:27:35