2017-03-22 31 views
1

我嘗試這個,但失敗。 __newindex僅在密鑰未設置時觸發。如何找出lua全局值何時設置爲零?

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}) 
+0

您需要設置的代理表全局表,又名'_ENV'在Lua 5.2+。 – lhf

+0

你能顯示更多細節嗎? –

+1

設置代理意味着僅使用專用表來捕獲寫入/閱讀事件。實際數據應該存儲在其他表中。這樣你總是會觸發__newindex。如何準確完成 - 取決於您的需求,因爲有很多組織數據的方法。 – Vlad

回答

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 

enter image description here

相關問題