全局索引错误 "self"?

error indexing global "self"?

我收到一个错误代码,告诉我它 "can't index local "self" - 一个数字值。"每当我通过 LOVE 启动游戏时。我一辈子都找不到错误。它阻碍了我的游戏进程,这真的很烦人。它是用 LUA/Love 格式写的,有人可以帮我吗?

local ent = ents.Derive("base")

function ent:load( x, y )
   self:setPos( x, y)
   self.w = 64
   self.h = 64
end

function ent:setSize( w, h )
   self.w = w
   self.h = h
end

function ent:getSize()
   return self.w, self.h;
end

function ent:update(dt)
   self.y = self.y + 32*dt
end

function ent:draw()
   local x, y = self:getPos()
   local w, h = self:getSize()

   love.graphics.setColor(0, 0, 0, 255)
   love.graphics.rectangle("fill", x, y, w, h )
end

return ent;

我在其他一些文件中调用了ent:update函数。 (注意上面的代码存储在另一个文件夹中,该文件夹包含所有实体 .lua 文件)

function ents:update(dt)
  for i, ent in pairs(ents.objects) do
    if ent.update(dt) then
      ent:update(dt)
    end
  end
end

function love.update(dt)
  xCloud = xCloud + 64*dt
  if xCloud >= (800 + 256) then
    xCloud = 0
  end
  yCloud = yCloud + 32*dt
  if yCloud >= (800 + 256) then
    yCloud = 0
  end
  zCloud = zCloud + 16*dt
  if zCloud >= (800 + 256) then
    zCloud = 0
  end
  ents:update(dt)
end

问题是您在 ents:update 函数中的 if ent.update(dt) then 调用。

你的意思是if ent:update(dt) then

: 函数调用语法只是语法糖,所以 ent:update(dt) 只是 ent.update(ent, dt) 的糖(这与 ent.update(dt) 明显不同,并解释了你的错误得到)。

有关此内容,请参阅 Lua 手册中的 Function Calls

A call v:name(args) is syntactic sugar for v.name(v,args), except that v is evaluated only once.

"can't index local "self" - a number value."

您这样定义 ent.update:

function ent:update(dt)
   self.y = self.y + 32*dt
end

这是语法糖:

function ent.update(self, dt)
   self.y = self.y + 32*dt
end

换句话说,它要求您将 self 作为第一个参数传递。

然后您这样调用 ent.update

if ent.update(dt) then
  ent:update(dt)
end

第 2 行是正确的。第 1 行不是。你正在为自己传递一个数字。当它试图索引时,你会得到 "can't index local 'self' - a number value".