简体   繁体   English

Lua OOP没有找到变量

[英]Lua OOP not finding variables

I'm trying to do OOP in Lua, but it's not letting me change the vel_y value in the checkInput{} method. 我正在尝试在Lua中进行OOP,但这并不是让我在checkInput {}方法中更改vel_y值。 Any ideas how i can get this to work? 任何想法我怎么能让这个工作? By the way I'm using Love2D for this input stuff. 顺便说一句,我正在使用Love2D来输入这些东西。

Player = {x = 100, y = 20, vel_x = 0, vel_y = 0}
function Player:new(o, x, y, vel_x, vel_y)
    o = o or {}   -- create object if user does not provide one
    setmetatable(o, self)
    self.__index = self
    length = 0
    return o
end

function Player:getX()
    return self.x
end

function Player:getY()
    return self.y
end

function Player:update( dt )
    --update velocity
    self.x = self.x + self.vel_x
    self.y = self.y + self.vel_y
    checkInput()

end

function checkInput( dt )

    if love.keyboard.isDown("w") and length < 5 then --press the right arrow key to push the ball to the right
        length = length + 1
        self.vel_y = 5
        print("bruhddddddddddddddddddddddd")
    elseif love.keyboard.isDown("a") then

    elseif love.keyboard.isDown("s") then

    elseif love.keyboard.isDown("d") then

  end
end

I assume your system call player:update() firs? 我假设您的系统调用player:update()会触发吗? If so you should pass self and dt to checkInput 如果是这样,您应该将selfdt传递给checkInput

function Player:update( dt )
    --update velocity
    self.x = self.x + self.vel_x
    self.y = self.y + self.vel_y
    checkInput(self, dt) --<--
end
...

function checkInput( self, dt )
...

if you define checkInput as local (of course before Player:update ) this may be similar to private method. 如果你将checkInput定义为local (当然在Player:update之前),这可能类似于private方法。

Player = {x = 100, y = 20, vel_x = 0, vel_y = 0} do
Player.__index = self -- we can do this only once

function Player:new(o, x, y, vel_x, vel_y)
  o = setmetatable(o or {}, self) -- create object if user does not provide one
  -- init o here
  return o
end

function Player:getX() end

function Player:getY() end

-- Private method
local function checkInput(self, dt) end

function Player:update( dt )
  ...
  checkInput(self, dt) -- call private method
end

end -- end clsss defenitioin

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM