how can i get a maximum number value in lua?

为君一笑 提交于 2020-01-30 13:07:33

问题


I am working on app to watch how fast you run, and for that I need a function that shows what your maximum speed has been. but can not find how I do.

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

I've made my speedText to a number that you see above.

I program in Conora SDK/Lua


回答1:


you should give more information when you ask questions on Stack Overflow, but let's try to help you anyway.

You code is probably inside an event listener that looks like that:

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

This displays the current speed. If you want to display the maximum speed instead, just do something like this:

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

The idea is: you need a variable defined outside the listener (or a global) to store the previous maximum speed. Every time the event listener is called, if the current speed is higher than the previous maximum speed, then it is the new maximum speed so you save it and you display it.



来源:https://stackoverflow.com/questions/14873537/how-can-i-get-a-maximum-number-value-in-lua

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!