"Attempt to index local 'self' (a nil value)" 无法对我的类的变量进行索引

我知道这个问题在这个网站上已经有几次了,但我的问题略有不同!所以...我的问题是,当我尝试在我写的玩家类的绘制函数中获取一个值时,发现当我尝试使用self.such'n'such时,它会说尝试索引本地变量'self'(一个空值),这些函数对我的问题并不重要(我希望)

require"functions"
Acc = 2000
Decel = 2500
Maxspd = 900

Player = {}
Player.__index = Player

function Player:new(x,y)
    local play = {}
    setmetatable(play, Player)
    play.inx = 0
    play.iny = 0
    play.dirx = 0
    play.diry = 0
    play.x = x
    play.y = y
    play.speedx = 0
    play.speedy = 0
    play.velx = 0
    play.vely = 0
    play.clr = "红色"
    play.hp = 100
    play.rot = 0
    play.size = 40
    play.hoehe = math.sqrt(3) * (40 / 2)
    return play
end

function love.load()
    Main = Player:new(100,100)
end

function Player:update(d)
    if love.keyboard.isDown("w") then self.iny = -1
    elseif love.keyboard.isDown("s") then self.iny = 1 else self.iny = 0 end
    if love.keyboard.isDown("d") then self.inx = 1
    elseif love.keyboard.isDown("a") then self.inx = -1 else self.inx = 0 end
    if self.inx == -self.dirx then self.speedx = self.speedx / 5 end
    if self.iny == -self.diry then self.speedy = self.speedy / 5 end
    self.dirx = self.inx
    self.diry = self.iny
    if self.inx ~= 0 then self.speedx = self.speedx + Acc * d
        else self.speedx = self.speedx - Decel * d end
    if self.iny ~= 0 then self.speedy = self.speedy + Acc * d
        else self.speedy = self.speedy - Decel * d end
    self.speedx = clamp(self.speedx,0,Maxspd)
    self.speedy = clamp(self.speedy,0,Maxspd)
    self.velx = self.speedx * d * self.dirx
    self.vely = self.speedy * d * self.diry
    self.x = self.x * d
    self.y = self.y * d
end

function Player:getX() return self.x end
function Player:getY() return self.y end

function Player:switch()
    if self.clr == "红色" then self.clr = "蓝色" end
    if self.clr == "蓝色" then self.clr = "红色" end
end

function Player:draw()
    local x1,x2,x3,y1,y2,y3 = 0,0,0,0,0,0
    x1 = self.x - self.size / 2
    y1 = self.y + self.hoehe / 2
    x2 = self.x + self.size/2
    y2 = self.y + self.hoehe / 2
    x3 = self.x
    y3 = self.y - self.hoehe / 2
    x1, y1 = rotate_around_point(x1, y1, self.x, self.y, self.rot)
    x2, y2 = rotate_around_point(x2, y2, self.x, self.y, self.rot)
    x3, y3 = rotate_around_point(x3, y3, self.x, self.y, self.rot)
    local verts = {x1,y1,x2,y2,x3,y3}
    if self.clr == "蓝色" then love.graphics.setColor(0,255,0,1) end
    if self.clr == "红色" then love.graphics.setColor(255,0,0,1) end
    love.graphics.polygon("fill",verts)
end

function love.keypressed(key,scancode,isrepeat)
    if key == "space" then Main:switch() end
end

function love.update(d)
    Main:update(d)
end

function love.draw()
    Main.draw()
end
点赞
用户6296866
用户6296866

我遇到同样的问题,@EgorSkriptunoff 的答案完全正确; 为了记忆起见,我要在这里发一个回答,而不是发表评论。

可能你是按照 x.f() 的方式调用函数而不是按照 x:f() 的方式。

2018-08-27 22:04:03