索引全局"self"时出错?

error indexing global "self"?

本文关键字:出错 self 全局 索引      更新时间:2023-10-16

每当我通过LOVE启动游戏时,我都会收到一个错误代码,告诉我"无法索引本地"self"-一个数值"。我无论如何也找不到那个错误。这阻碍了我的游戏进程,这真的很烦人。它是用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

"不能索引本地"self" -一个数值。"

你定义了。像这样更新:

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

第二行是正确的。1号线不是。你在给自己传号码。当它试图索引时,你会得到"不能索引本地'self' -一个数值"。

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

你说的是if ent:update(dt) then

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

参见Lua手册中的函数调用。

调用v:name(args)是v.name(v,args)的语法糖,只是v只求值一次。