[英]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
我也試過重命名變量,也許它們會與類 width -> self.width 的內部方法發生沖突,但即使我將它們稱為 a,b,c 也會發生同樣的事情。
你忘了:
這樣你只需要3個PARAMS,而不是預期的4 centerCoordinatesOn
,當你調用self.ball.centerCoordinatesOn(1,1,1)
這是因為當你定義
Ball:centerCoordinatesOn(x, y, width)
編寫此定義的另一種方法是
Ball.centerCoordinatesOn(self, x, y, width)
任何一個定義width
都是第四個參數,在您當前的調用中最終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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.