调用自身函数出现的 Bug?

我写了这段代码:

Editor = {
  x = 10,
  y = 10,
  interpreter = nil,
  cursor = nil
}

-- 这里有些代码

function Editor:drawValues(w, h)
  for x = 0, w - 1 do
    for y = 0, h - 1 do
      local _x = self.x + x * CELL_SIZE
      local _y = self.y + y * CELL_SIZE
      love.graphics.print(self.interpreter.grid.cell[x][y], _x, _y) -- 错误出在这里!
    end
  end
end

function Editor:draw()
  local w = self.interpreter.grid.width
  local h = self.interpreter.grid.height

  Editor:drawGrid(w, h)
  Editor:drawValues(w, h)

  -- 下面这些可行 VVVVVVV
  -- for x = 0, w - 1 do
  --   for y = 0, h - 1 do
  --     local _x = self.x + x * CELL_SIZE
  --     local _y = self.y + y * CELL_SIZE
  --     local value = self.interpreter.grid.cell[x][y]
  --     love.graphics.print(value, _x, _y) -- self.interpreter.grid.cell[x][y]
  --   end
  -- end
end

return Editor

函数 Editor:draw 调用了 Editor:drawGrid 并且它可以正常工作,但是调用 Editor:drawValues(w, h) 就会出现错误:

attempt to index field 'interpreter' (a nil value)

但!如果我将 Editor:drawValues(w, h) 注释掉并取消下面那段代码的注释,它就能正常工作了。为什么呢?

非常抱歉我的英语不好。

点赞