Proxies
Problem Definition Assume that all accesses to a table are to be:
- Tracked
- Limited
- Modified
- Some of the above
Problem Solution Discussion
1\. Some type of Proxy standing in front of the table should be present<br> 2\. The proxy needs to call some function for every read or write to the table 3\. One suggestion is to use the __index and __newindex metamethods. With an empty table that acts as the proxy This suggestion is used for the following code The solutions are taken with some modifications from Programming in Lua by Roberto Ierusalimschy ``` _**Solution 1**_ ``` --[[In this code the task is to monitor all accesses to a table. To do this we create a proxy for the table. This is an empty table that has both __index and __newIndex metamethods. Each call is made to the proxy table which checks the calls and then passes them onto the real table.]] theTable = {} local _t = theTable theTable = {} local mt = { __index = function( table, key) print("*access to element " .. tostring(key)) return _t[key] end, __newindex = function(table, key, value) print("*update of element " .. tostring(key) .. " to " .. tostring(value)) _t[key] = value end } setmetatable(theTable, mt) theTable[2] = "hello" print(theTable[2]) ```