Exercise 21.4: A variation of the dual representation is to implement objects using proxies (the section called “Tracking table accesses”). Each object is represented by an empty proxy table. An internal table maps proxies to tables that carry the object state. This internal table is not accessible from the outside, but methods use it to translate their self parameters to the real tables where they operate. Implement the Account example using this approach and discuss its pros and cons.
local AccountProxy = {}
-- Internal table mapping proxies to actual Account tables
local accounts = {}
function AccountProxy:new()
local proxy = {}
local account = {balance = 0}
accounts[proxy] = account
setmetatable(proxy, {
__index = self,
})
return proxy
end
function AccountProxy:withdraw(v)
accounts[self].balance = (accounts[self].balance or 0) - v
end
function AccountProxy:deposit(v)
accounts[self].balance = (accounts[self].balance or 0) + v
end
function AccountProxy:getBalance()
return accounts[self].balance or 0
end
-- Example usage
local acc_1 = AccountProxy:new() -- acc_1 is the proxy
acc_1.deposit(100.0)
print(acc_1.getBalance()) -- 100.0
acc_1.withdraw(50.0)
print(acc_1.getBalance()) -- 50.0
I get attempt to index a nil value (field '?'). Any suggestion?
I need encapsulation on Account object and balance as Account's property