c++ - 索引全局 "self"时出错?

标签 c++ lua love2d

我收到一个错误代码,告诉我它“无法索引本地“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

最佳答案

"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 行不是。你正在为自己传递一个数字。当它尝试为其编制索引时,您会得到“无法为本地‘self’编制索引 - 一个数字值”。

关于c++ - 索引全局 "self"时出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33129407/

相关文章:

c++ - 如何查看C++中的标准库函数?

lua - luajit 上不受欢迎的 if 语句

lua - Lua中的模块化代码结构

lua - 为什么 LuaJIT 从这个简单的代码中产生 "too many callbacks error"?

c++ - 段错误 : "...no such file or directory"

c++ - 在声明和初始化指针后,什么时候给变量字面量加上星号前缀,什么时候不用?

Java:嵌入到 Java 桌面应用程序中的脚本语言(宏)

for-loop - Lua 二维数组错误

c++ - C++11 中的优雅时间打印

parsing - 哪些语法可以使用递归下降而不回溯来解析?