Last active
May 16, 2022 20:29
-
-
Save dextercd/2a3db3ef9b5933db876d8835671502a2 to your computer and use it in GitHub Desktop.
This file contains 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
function shallow_copy(t) | |
local t2 = {} | |
for k,v in pairs(t) do | |
t2[k] = v | |
end | |
return t2 | |
end | |
local function make_observable(t, key, prev_keys) | |
if type(t) ~= "table" then | |
return | |
end | |
local prev_keys = prev_keys or {} | |
local _data = {} | |
if key then | |
table.insert(prev_keys, key) | |
end | |
for k, v in pairs(t) do | |
make_observable(v, k, shallow_copy(prev_keys)) | |
end | |
setmetatable(t, { | |
__index = function(self, key) | |
return _data[key] | |
end, | |
__newindex = function(self, key, value) | |
if type(value) == "table" then | |
make_observable(value, key, shallow_copy(prev_keys)) | |
end | |
_data[key] = value | |
path = table.concat(prev_keys, ".") | |
if path ~= '' then | |
path = path .. '.' | |
end | |
path = path .. key | |
print(path .. " changed!") | |
end | |
}) | |
end | |
local data = {} | |
make_observable(data) | |
data.one = { boo = 5 } | |
data.blob = { ding = { dong = {} } } | |
data.blob.ding.dong.hey = 'hi' |
This file contains 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
$ lua5.1 mt.lua | |
one changed! | |
blob changed! | |
blob.ding.dong.hey changed! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment