luaphysics

If statement returns nil


I am trying to make a speed calculator that takes speed input and distance needed to cover input and it should return the time needed to cover this distance based on the formula 'speed = distance / time', I also make the user input km if the distance is in kilometers or m if the distance is in meters and I use an If statement to turn the kilometers into meters.

io.write("enter speed(m/s):")
local speed = io.read()
io.write("enter distance needed:")
local distance = io.read()
io.write("specify((m) or(km)):")
local units = io.read()

local meters = "m"
local kilometers = "km"
local hundred

if units == meters then 
    local usedist = distance
elseif units == kilometers then 
    local usedist = distance * hundred
else
    io.write("you did not enter a valid character, please restart the program by pressing 'enter'")
    io.read()
end
print(usedist)
local timeneeded = usedist / speed
local timeneededh = timeneeded / 3600

os.execute("cls")

io.write("it will need "..timeneeded.." seconds or "..timeneededh.." hours")


io.write("\n")
io.write("press the 'enter' key to continue")
io.read()

I was expecting a value of time in seconds but I got this

enter speed(m/s):5
enter distance needed:9
specify((m) or(km)):km
C:\Lua\lua54.exe: object-time-calc.lua:15: attempt to mul a 'string' with a 'nil'
stack traceback:
        [C]: in metamethod 'mul'
        object-time-calc.lua:15: in main chunk
        [C]: in ?

Solution

  • usedist is local to within the if block where you defined it. Declare it in front of it in order to be able to access it later, like this.

    local usedist
    if units == meters then 
        usedist = distance
    elseif units == kilometers then 
        usedist = distance * hundred
    else