简体   繁体   English

零值崩溃 - Love2D Lua

[英]Crash on nil value - Love2D Lua

I'm instantiating a ball and it works well, when I try to call centerCoordinatesOn it crashes.我正在实例化一个球并且它运行良好,当我尝试调用centerCoordinatesOn它崩溃了。

Ball = Class{}

function Ball:init(skin)
    -- simple positional and dimensional variables
    self.width = 8
    self.height = 8

    -- these variables are for keeping track of our velocity on both the
    -- X and Y axis, since the ball can move in two dimensions
    self.dy = 0
    self.dx = 0

    -- this will effectively be the color of our ball, and we will index
    -- our table of Quads relating to the global block texture using this
    self.skin = skin

    self.needsStartup = true
end

function Ball:centerCoordinatesOn(x, y, width)
    print(x.." "..y.." "..width)--attempt to concatenate local 'width' (a nil value)
    self.x = x + (width / 2) - 4
    self.y = y - 8
end




self.ball = Ball()
self.ball.skin = math.random(7)    
self.ball.centerCoordinatesOn(1,1,1)--crash

If I remove the method and just call the content of it manually it works fine:如果我删除该方法并手动调用它的内容,它可以正常工作:

self.ball.x = 1 + (1 / 2) - 4
self.ball.y = 1 - 8

I've also tried renaming the variables, maybe they would conflict with the internal methods of the class width -> self.width, but the same things happed even if I call them a,b,c.我也试过重命名变量,也许它们会与类 width -> self.width 的内部方法发生冲突,但即使我将它们称为 a,b,c 也会发生同样的事情。

You forgot the : so you only have 3 params rather than the 4 expected by centerCoordinatesOn , when you call self.ball.centerCoordinatesOn(1,1,1)你忘了:这样你只需要3个PARAMS,而不是预期的4 centerCoordinatesOn ,当你调用self.ball.centerCoordinatesOn(1,1,1)

This is because when you defined这是因为当你定义

Ball:centerCoordinatesOn(x, y, width)

an alternate way to write this definition is编写此定义的另一种方法是

Ball.centerCoordinatesOn(self, x, y, width)

with either definition width is the 4th param, which ends up nil with your current call.任何一个定义width都是第四个参数,在您当前的调用中最终nil

So your call of self.ball.centerCoordinatesOn(1,1,1) should be:所以你对self.ball.centerCoordinatesOn(1,1,1)调用应该是:

self.ball:centerCoordinatesOn(1,1,1) --note the : after ball.
-- or --
self.ball.centerCoordinatesOn(self.ball, 1, 1, 1) --note first param is ball.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM