Lua面向对象编程中找不到变量

我正在尝试在Lua中实现面向对象编程,但在checkInput{}方法中无法改变vel_y值。有什么办法可以让这个工作?顺便说一句,我在使用Love2D处理输入方面。

点赞
用户2328287
用户2328287

假设你的系统调用了 player:update() 吗?如果是这样的话,你应该将 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 )
...

如果你把 checkInput 定义为 local(当然要在 Player:update 之前),这就类似于私有方法。

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

-- 私有方法
local function checkInput(self, dt) end

function Player:update( dt )
  ...
  checkInput(self, dt) -- 调用私有方法
end

end -- end class definition
2015-02-11 11:36:11