如何找出 lua 全局变量何时被设置为 nil?

我尝试过这个方法,但是失败了。__newindex 只在键没有被设置时才会触发。

setmetatable(_G, {
__newindex = function (table, key, value)
print("key: ", key, "value: ", value)
rawset(table, key, value)
if key == "Config" then
    print("value: ", value)
    if value == nil then
        error(debug.traceback())
    end
end
end})
点赞
用户2045424
用户2045424

以下代码有效:

local m = {}
local t = {
    __newindex = function (table, key, value)
        m[key] = value
        if key == "Config" then
            print("config value: ", value)
        if value == nil then
            error("Config is set to nil!!!!!!"..debug.traceback())
        end
    end
end,
__index = m}
setmetatable(_G, t)

Config = Config or {}
Config = nil

[![进入图片描述](https://i.stack.imgur.com/Svp2w.png)](https://i.stack.imgur.com/Svp2w.png)

2017-03-23 11:41:44