【问题标题】:Lua - print the result of a function calculationLua - 打印函数计算的结果
【发布时间】:2019-01-02 01:53:24
【问题描述】:

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

local celsiustemp = 37.5

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

toFahrenheit(celsiustemp)

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

产生的错误如下。

lua: 将 c 转换为 f.lua:9: 尝试连接一个函数值 (本地'toFahrenheit')堆栈回溯:将c转换为f.lua:9:在main 块 [C]: 在 ?

我是 Lua 的新手,所以我不确定我错过了什么?任何帮助都非常感谢..

【问题讨论】:

    标签: lua


    【解决方案1】:

    函数的每次调用都会返回值,因此您必须将函数结果存储到变量中或在打印函数本身中调用函数:

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

    您可能还想了解更多关于函数调用的信息,因为这通常是所有编程语言使用的相同方法;它就像一个返回值的数学函数,但您必须将该值存储在某个地方,或者您可以像我在 print 函数中那样直接使用它。

    【讨论】:

      【解决方案2】:

      你已经接近了!试试:

      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))
      

      【讨论】:

        猜你喜欢
        • 2014-06-03
        • 2015-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多