变量是nii?

Variable is nii?

我最近在用LOVE2D和Lua制作游戏。我正在更新 Breakout,我在 Paddle.lua.

中遇到错误

代码:

Paddle = Class{}

--[[
    Our Paddle will initialize at the same spot every time, in the middle
    of the world horizontally, toward the bottom.
]]

size = math.random(4)

function Paddle:init(skin, size)
    -- x is placed in the middle
    self.x = VIRTUAL_WIDTH / 2 - 32

    -- y is placed a little above the bottom edge of the screen
    self.y = VIRTUAL_HEIGHT - 32

    -- start us off with no velocity
    self.dx = 0
    
    self.size = size
    
    self.height = 16
    if self.size == 1 then
        self.width = 32
    elseif self.size == 3 then
        self.width = 96
    elseif self.size == 4 then
        self.width = 128
    else
        self.width = 64
    end

    -- the skin only has the effect of changing our color, used to offset us
    -- into the gPaddleSkins table later
    self.skin = skin
end

function Paddle:update(dt)
    -- keyboard input
    if love.keyboard.isDown('left') then
        self.dx = -PADDLE_SPEED
    elseif love.keyboard.isDown('right') then
        self.dx = PADDLE_SPEED
    else
        self.dx = 0
    end

    -- math.max here ensures that we're the greater of 0 or the player's
    -- current calculated Y position when pressing up so that we don't
    -- go into the negatives; the movement calculation is simply our
    -- previously-defined paddle speed scaled by dt
    if self.dx < 0 then
        self.x = math.max(0, self.x + self.dx * dt)
    -- similar to before, this time we use math.min to ensure we don't
    -- go any farther than the bottom of the screen minus the paddle's
    -- height (or else it will go partially below, since position is
    -- based on its top left corner)
    else
        self.x = math.min(VIRTUAL_WIDTH - self.width, self.x + self.dx * dt)
    end
end

--[[
    Render the paddle by drawing the main texture, passing in the quad
    that corresponds to the proper skin and size.
]]
function Paddle:render()
    love.graphics.draw(gTextures['main'], gFrames['paddles'][self.size + 4 * (self.skin - 1)],
        self.x, self.y)
end

错误:

Error

src/Paddle.lua:83: attempt to perform arithmetic on field 'size' (a nil value)


Traceback

src/Paddle.lua:83: in function 'render'
src/states/ServeState.lua:68: in function 'render'
src/StateMachine.lua:26: in function 'render'
main.lua:210: in function 'draw'
[C]: in function 'xpcall'

虽然我赋值了,但是说是nii。我该如何解决这个问题?

函数参数是函数体的局部参数。所以在 Paddle.Init size 里面是一个局部变量,它隐藏了全局变量 size.

当您在未提供 size 参数的情况下调用 Paddle.Init 时,size 在导致观察到的错误的函数中是 nil

Wikipedia: Variable Shadowing

很多人使用前缀来表示全局变量。 g_size 例如。然后你可以这样做:

g_size = 4

function Paddle:Init(skin, size)
  self.size = size or g_size
end

如果未提供 size 参数,这将使 self.size 默认为 g_size

另一种选择是以您的全局大小作为输入来调用球拍构造函数。