lua 找不到已定义的全局变量,试图索引全局变量 ...(一个空值)。

我确信自己错过了某个非常简单的东西,但我盯着看了好久,仍然需要你们的帮助。我正在尝试编写最简单的日志记录器,但当我尝试运行它时,它没有看到全局变量(我(认为)已经声明了!)。我在 Lua 中是一个“高级”的初学者,所以愚蠢的错误不太常见,但在我这种情况下仍然会发生。请告诉我我在这里失去了什么!

以下是记录器代码,我正在脚本中进行测试……

local type, pairs, table, tostring, io, os, print = type,pairs,table,tostring,io,os,print
local file
LEVELS = {}
LEVELS ["ERROR"] = 0
LEVELS ["WARN"] = 1
LEVELS ["INFO"] = 2
LEVELS ["DEBUG"] = 3
print(LEVELS.WARN)
local level

function init(outputFile,debugLevel)
  level = debugLevel
  file = io.open(outputFile,“a”)
  local ret
  if(file == nil)then ret = false else ret = true end
  return ret
end

function warn(message)
   if level ~= nil and level >= LEVELS.WARN and file ~= nil then
     log(message)
   end
end
function log(message)
   local timestamp = os.date()

    file :write(timestamp ..' - '.. message ..'\ n')
    file :flush()
end

function deInit()
   file :close()
end

init(“testInsideLogger.lua”,3)
warn(“HI”)
deInit()

我在输出中得到的结果:

在声明 LEVELS 右侧的 Print 中有效,输出结果为 1。

但是当我调用 warn(“HI”)方法时,我得到了

尝试索引全局变量 'LEVELS' (值为空)。

为什么?

非常感谢你们的帮助!

点赞