Переменная nii? - PullRequest
0 голосов
/ 10 июля 2020

Я недавно использую 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 хотя назначил. Как это исправить?

1 Ответ

3 голосов
/ 10 июля 2020

Параметры функции являются локальными для тела функции. Таким образом, внутри Paddle.Init size находится локальная переменная, которая затеняет глобальную переменную size.

Когда вы вызываете Paddle.Init без указания параметра size, size равно nil внутри

См. Википедия: Затенение переменных

Многие люди используют префикс для обозначения глобальных переменных. g_size например. Затем вы можете сделать что-то вроде:

g_size = 4

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

Что сделает self.size значение по умолчанию g_size, если параметр size не указан.

Другой вариант - вызвать ракетку конструктор с вашим глобальным размером в качестве входных.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...