Created
October 6, 2016 13:27
-
-
Save patricksuo/b02a08023dabdec3ddf657b68ebe1c8d to your computer and use it in GitHub Desktop.
lua proxy demo
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
| proxy = {} | |
| proxy.wrap = function(t) | |
| return proxy.wraphelper(t, nil, nil) | |
| end | |
| proxy.wraphelper = function(t, pm, path2me) | |
| -- print("wraphelper", t, pm, path2me) | |
| local m = {} | |
| m.__path = path2me | |
| m.__parent = pm | |
| m.__newindex = function(_, k, v) | |
| local old = t[k] | |
| -- print("set", "path", path, "old", old, "new", v) | |
| -- trace new table | |
| local wv = v | |
| if old == nil and type(v) == "table" then | |
| wv = proxy.wraphelper(v, m, k) | |
| end | |
| local path = tostring(k) | |
| if m.__parent ~= nil then | |
| path = path .. "<=" | |
| path = path .. tostring(m.__path) | |
| end | |
| local parent = m.__parent | |
| while parent ~= nil and parent.__path ~= nil do | |
| path = path .. "<=" | |
| path = path .. tostring(parent.__path) | |
| parent = parent.__parent | |
| end | |
| print("set", "*", path, "*", k, "old", old, "new", v) | |
| t[k] = wv | |
| end | |
| m.__index = function(_, k) | |
| return t[k] | |
| end | |
| p = {} | |
| setmetatable(p, m) | |
| return p | |
| end | |
| t1 = proxy.wrap({}) | |
| t1.backpack = {} | |
| t1.backpack[1] = {id=1, power=100} | |
| t1.backpack[1].power = 101 | |
| print(t1.backpack[1].power) | |
| t1.mailbox = {} | |
| table.insert(t1.mailbox, {}) | |
| t1.mailbox[1].mail_id = 1 | |
| t1.mailbox[1].content = "foo" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment