试图访问表中的表值

Wiz*_*zix 1 lua

我正在努力做到这一点

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 }
    }
Run Code Online (Sandbox Code Playgroud)

但Love2D说我attempt to perform arithmetic on global 'width' (a nil value).我该如何解决?
我已经尝试过替换width / 2,ball.width / 2但我得到了attempt to index global 'ball' (a nil value).

Nic*_*las 5

请记住,这local some_name = expression相当于:

local some_name
some_name = expression
Run Code Online (Sandbox Code Playgroud)

这允许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)
}
Run Code Online (Sandbox Code Playgroud)