怎样在 Lua 中取得最大数值?

我正在开发一个能够监测你跑得有多快的应用程序,我需要一个函数来显示你的最高速度,但我找不到如何实现。

local speedText = string.format( '%.3f', event.speed )
speed.y = 250
speed.x = 125
local numValue = tonumber(speedText)*3.6
if numValue ~= nil then
    speed.text = math.round( numValue )
end

我已经将speedText转换成上面所看到的数字。

我使用的是Conora SDK/Lua进行编程。

点赞
用户204011
用户204011

你应该在 Stack Overflow 上提问时提供更多的信息,但是我们还是来帮你的。

你的代码可能在一个事件监听器中,类似这样:

local listener = function(event)
  local speedText = string.format( '%.3f', event.speed )
  speed.y = 250
  speed.x = 125
  local numValue = tonumber(speedText)*3.6
  if numValue ~= nil then
      speed.text = math.round( numValue )
  end
end

这段代码显示了当前速度。如果你想显示最大速度,可以这样做:

local maxSpeed = 0
local listener = function(event)
  local speedText = string.format( '%.3f', event.speed )
  speed.y = 250
  speed.x = 125
  local numValue = tonumber(speedText)*3.6 or 0
  if numValue > maxSpeed then
      maxSpeed = numValue
      speed.text = math.round( numValue )
  end
end

这个想法是:你需要在监听器之外定义一个变量(或者全局变量)来存储前一次的最大速度。每次监听器被调用时,如果当前速度高于之前的最大速度,那么它就是新的最大速度,所以你保存它并显示它。

2013-02-14 13:44:57