我试图这样做
local ball = {
width = 20,
height = 20,
position = {
x = (game.width / 2) - (width / 2), -- Place the ball at the center of the screen
y = (game.height / 2) - (height / 2)
},
velocity = 200,
color = { 255, 255, 255 }
}
但Love2D说我attempt to perform arithmetic on global 'width' (a nil value)
。我该如何解决?
我已尝试将width / 2
替换为ball.width / 2
,但我得到attempt to index global 'ball' (a nil value)
。
答案 0 :(得分:5)
请记住,local some_name = expression
相当于:
local some_name
some_name = expression
这允许some_name
出现在expression
中。特别是,它允许使用本地函数进行递归。但是,在expression
实际完成评估之前,some_name
的值仍为nil
。
因此,在您的表初始化中,ball
是nil
值。在初始化该表时,无法访问表的成员。不过你可以这样做:
local ball = {
width = 20,
height = 20,
velocity = 200,
color = { 255, 255, 255 }
}
ball.position = {
x = (game.width / 2) - (ball.width / 2), -- Place the ball at the center of the screen
y = (game.height / 2) - (ball.height / 2)
}