试图访问表中的表值

时间:2016-04-21 18:56:20

标签: 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 }
    }

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

1 个答案:

答案 0 :(得分:5)

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

local some_name
some_name = expression

这允许some_name出现在expression中。特别是,它允许使用本地函数进行递归。但是,在expression实际完成评估之前,some_name仍为nil

因此,在您的表初始化中,ballnil值。在初始化该表时,无法访问表的成员。不过你可以这样做:

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)
}