'I'm getting an error: "attempt to compare nil with number" in Lua with LOVE2d

I'm trying to make my first game with lua & love, it's a simple button clicker game that counts how many times you click a randomly appearing button. I'm trying to add a timer that counts down from 20 on the screen (and eventually make it so that an end screen appears when the timer hits 0).

function love.update(dt)
  t = t + 0.01
end

function love.load (timer)
  while t > 0 do
    if t % 1 == 0 then
      timer = 1 + timer
    end
  end
end

But I get this error: "attempt to compare nil with number" I've searched and found tonumber() but I don't know how to use it properly. I'm not even sure that this is the best/a way to make a timer... help?



Solution 1:[1]

love will call your love.load. When evaluating your while condition t > 0 it will throw this error because t is not a number but a nil value. You need to initialize t with a number value befor you can compare it with another number.

I don't mean this offensive but your code does not make too much sense.

First of all you never initialized t with a value. So you cannot do any operations on it.

function love.update(dt)
  t = t + 0.01
end

love.load is executed once at the beginning of your game. timer is actually a table value containing the command line arguments to your game. So adding increasing it by 1 does not make any sense.

function love.load (timer)
  while t > 0 do
    if t % 1 == 0 then
      timer = 1 + timer
    end
  end
end

Even if t was a number, t % 1 is always 0. So comparing it with 0 doesn't make sense. Plus your code doesn't do anything aside from attempting to increase values by 1 or 0.01 respectively.

Make sure you refer to the love and Lua manuals for everything you use.

https://love2d.org/wiki/love.run <- this is very important so you understand how those functions are executed.

https://love2d.org/wiki/love

Solution 2:[2]

try adding:

function love.load()
    t = 0
end

i also noticed the while t > 0 do in love.load(), this will not work as you expect, instead try putting it in love.update(dt)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Piglet
Solution 2