Last active
November 11, 2024 06:36
-
-
Save outsinre/37dcac5b289f17511a1832903e901924 to your computer and use it in GitHub Desktop.
Monitor Lua table access and update
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- table to monitor | |
ori_t = { a = "b" } | |
-- a proxy table - must be empty | |
proxy_t = {} | |
local mt | |
do | |
mt = { | |
__index = function (self, k) | |
print("*get key " .. tostring(k)) | |
return ori_t[k] -- access the original table | |
end, | |
__newindex = function (self, k, v) | |
print("*set key " .. tostring(k) .. | |
" to " .. tostring(v)) | |
ori_t[k] = v -- update original table | |
end | |
} | |
end | |
setmetatable(proxy_t, mt) | |
proxy_t[2] = 'hello' | |
print(proxy_t[2]) | |
print(proxy_t["a"]) | |
proxy_t["a"] = 'c' | |
print(proxy_t["a"]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Refer to https://stackoverflow.com/questions/57598440/is-there-a-way-to-listen-for-changes-in-a-lua-table.