Skip to content

Instantly share code, notes, and snippets.

@dextercd
Last active May 16, 2022 20:29
Show Gist options
  • Save dextercd/2a3db3ef9b5933db876d8835671502a2 to your computer and use it in GitHub Desktop.
Save dextercd/2a3db3ef9b5933db876d8835671502a2 to your computer and use it in GitHub Desktop.
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'
$ 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