零值时崩溃 - Love2D Lua
Crash on nil value - Love2D Lua
我正在实例化一个球并且它运行良好,当我尝试调用 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
如果我删除该方法并手动调用它的内容,它就可以正常工作:
self.ball.x = 1 + (1 / 2) - 4
self.ball.y = 1 - 8
我也试过重命名变量,也许它们会与 class width -> self.width 的内部方法冲突,但即使我称它们为 a,也会发生同样的事情, b,c.
你忘记了 :
所以当你调用 self.ball.centerCoordinatesOn(1,1,1)
时你只有 3 个参数而不是 centerCoordinatesOn
期望的 4 个
这是因为当您定义
Ball:centerCoordinatesOn(x, y, width)
编写此定义的另一种方法是
Ball.centerCoordinatesOn(self, x, y, width)
无论哪种定义,width
都是第 4 个参数,它以您当前的调用结束 nil
。
所以你对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.
我正在实例化一个球并且它运行良好,当我尝试调用 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
如果我删除该方法并手动调用它的内容,它就可以正常工作:
self.ball.x = 1 + (1 / 2) - 4
self.ball.y = 1 - 8
我也试过重命名变量,也许它们会与 class width -> self.width 的内部方法冲突,但即使我称它们为 a,也会发生同样的事情, b,c.
你忘记了 :
所以当你调用 self.ball.centerCoordinatesOn(1,1,1)
centerCoordinatesOn
期望的 4 个
这是因为当您定义
Ball:centerCoordinatesOn(x, y, width)
编写此定义的另一种方法是
Ball.centerCoordinatesOn(self, x, y, width)
无论哪种定义,width
都是第 4 个参数,它以您当前的调用结束 nil
。
所以你对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.