Lua - 打印函数计算结果

我正在尝试打印在函数内进行的计算的结果

local celsiustemp = 37.5

local function toFahrenheit(c)
return c * 9 / 5 + 32
end

toFahrenheit(celsiustemp)

print("Temp in Celsius = '" .. toFahrenheit )

出现的错误如下所示:

lua: convert c to f.lua:9: attempt to concatenate a function value (local 'toFahrenheit') stack traceback: convert c to f.lua:9: in main chunk [C]: in ?

我是 Lua 的新手,所以不知道自己漏了什么?非常感谢您的帮助。

点赞
用户734069
用户734069

每次调用函数都会返回一个值,因此您必须将函数结果存储到变量中或在打印函数内部调用该函数:

local ftemp = toFahrenheit(celsiustemp)
print(celsiustemp .. " in fahrenheit: " .. ftemp)

此外,您可能希望学习更多关于函数调用的知识,因为这通常是所有编程语言使用的相同方法;它就像返回一个值的数学函数,但是您必须将该值存储在某个地方或直接在打印函数中使用,就像我所做的那样。

2018-07-25 09:45:38
用户4403144
用户4403144

你快成功了!试试以下代码:

local celsiustemp = 37.5

local function toFahrenheit(c)
    return c * 9 / 5 + 32
end

print("Temp in Fahrenheit = " .. toFahrenheit(celsiustemp))

错误消息表明你在连接函数本身而不是函数的结果,这个结果是在你实际调用它时得到的(使用())。换句话说:

不可以这样做:

print("Temp in Fahrenheit = " .. toFahrenheit)

但你可以这样:

print("Temp in Fahrenheit = " .. toFahrenheit(celsiustemp))
2018-07-25 23:51:21