[英]Lua OOP not finding variables
我正在嘗試在Lua中進行OOP,但這並不是讓我在checkInput {}方法中更改vel_y值。 任何想法我怎么能讓這個工作? 順便說一句,我正在使用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
我假設您的系統調用player:update()會觸發嗎? 如果是這樣,您應該將self
和dt
傳遞給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
之前),這可能類似於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.