Created
August 2, 2024 09:42
-
-
Save DimaCrafter/46004dc878b2f454f4e188d1fa248c97 to your computer and use it in GitHub Desktop.
Simple get/set proxy for a table on Lua
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
| Document = {} | |
| function Document.new (raw) | |
| local doc = {} | |
| Document.attach_deep_proxy(raw, doc) | |
| return doc | |
| end | |
| function Document.attach_deep_proxy (raw, doc, path) | |
| if path == nil then | |
| path = {} | |
| end | |
| for key, value in pairs(raw) do | |
| if type(value) == 'table' then | |
| local sub_path = table.icopy(path) | |
| push(sub_path, key) | |
| doc[key] = {} | |
| Document.attach_deep_proxy(value, doc[key], sub_path) | |
| end | |
| end | |
| setmetatable(doc, { | |
| __index = function (_, key) | |
| Document._get(raw, key, doc, path) | |
| return raw[key] | |
| end, | |
| __newindex = function (_, key, value) | |
| raw[key] = value | |
| if type(value) == 'table' then | |
| local sub_path = table.icopy(path) | |
| push(sub_path, key) | |
| rawset(doc, key, {}) | |
| Document.attach_deep_proxy(value, rawget(doc, key), sub_path) | |
| end | |
| Document._set(raw, key, value, doc, path) | |
| end, | |
| __len = function () | |
| return #raw | |
| end | |
| }) | |
| end | |
| function Document._get (raw, key, doc, path) | |
| print(':get', key, 'at', table.concat(path, '->')) | |
| end | |
| function Document._set (raw, key, value, doc, path) | |
| print(':set', key, 'at', table.concat(path, '->'), 'to', value) | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment