[英]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.我正在尝试使用 lua 和爱来制作我的第一款游戏,这是一款简单的按钮点击游戏,可以计算您点击随机出现的按钮的次数。 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).
我正在尝试添加一个从屏幕上的 20 开始倒计时的计时器(并最终使其在计时器达到 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.但是我收到了这个错误:“尝试将 nil 与数字进行比较”我已经搜索并找到
tonumber()
但我不知道如何正确使用它。 I'm not even sure that this is the best/a way to make a timer... help?我什至不确定这是制作计时器的最佳/方法...帮助?
love will call your love.load
.爱会打电话给你的
love.load
。 When evaluating your while condition t > 0
it will throw this error because t is not a number but a nil value.在评估您的 while 条件
t > 0
时,它会抛出此错误,因为 t 不是数字而是 nil 值。 You need to initialize t with a number value befor you can compare it with another number.您需要用一个数字值初始化 t,然后才能将其与另一个数字进行比较。
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.首先,您从未用值初始化
t
。 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. love.load 在游戏开始时执行一次。
timer
is actually a table value containing the command line arguments to your game. timer
实际上是一个表值,其中包含您游戏的命令行 arguments。 So adding increasing it by 1 does not make any sense.因此,将其增加 1 没有任何意义。
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
.即使
t
是一个数字, t % 1
也总是0
。 So comparing it with 0
doesn't make sense.因此,将其与
0
进行比较是没有意义的。 Plus your code doesn't do anything aside from attempting to increase values by 1 or 0.01 respectively.另外,除了尝试将值分别增加 1 或 0.01 之外,您的代码不会做任何事情。
Make sure you refer to the love and Lua manuals for everything you use.确保您参考爱和 Lua 手册以了解您使用的所有内容。
https://love2d.org/wiki/love.run <- this is very important so you understand how those functions are executed. https://love2d.org/wiki/love.run <- 这非常重要,因此您了解这些功能是如何执行的。
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)
我还注意到
while t > 0 do
in love.load()
,这不会像您期望的那样工作,而是尝试将其放入love.update(dt)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.