【问题标题】:How to find out when lua global value is set to nil?如何找出lua全局值何时设置为nil?
【发布时间】:2017-08-14 10:19:46
【问题描述】:

我尝试了这个,但失败了。 __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})

【问题讨论】:

  • 你需要为全局表设置一个代理表,也就是 Lua 5.2+ 中的_ENV
  • 你能提供更多细节吗?
  • 设置代理意味着只使用专用表来捕获写/读事件。实际数据应存储在其他表中。这样你总是会触发 __newindex。如何准确地做到这一点 - 取决于您的需求,因为有很多组织数据的方法。
  • 谢谢,我明白了。

标签: lua lua-table


【解决方案1】:

以下代码有效:

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

【讨论】:

    猜你喜欢
    • 2019-03-01
    • 2017-04-23
    • 2019-08-21
    • 2021-08-04
    • 2014-04-01
    • 2018-07-11
    • 2014-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多