错误索引全局"self"?

每当我通过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
点赞
用户258523
用户258523

问题出在 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

调用 v:name(args) 仅是将 v.name(v,args) 换成了语法糖,只是 v 只被计算一次。

2015-10-14 17:09:06
用户501459
用户501459

你定义了 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

第二行是正确的。但是第一行不对,你给 self 传递了一个数字。当它尝试对其进行索引时,就会出现"can't index local 'self' - a number value"的错误。

2015-10-14 17:14:00