-- Exercise 21.4 -- :
local AccountProxy = {}
local accounts = {}
function AccountProxy:new()
local proxy = {}
local account = {}
accounts[proxy] = account
setmetatable(proxy, {
__newindex = function(_, k, v)
account[k] = v
end,
__index = function(_, k)
return account[k]
end,
})
return proxy
end
function AccountProxy:withdraw(v)
self.balance = (self.balance or 0) - v
end
function AccountProxy:deposit(v)
self.balance = (self.balance or 0) + v
end
function AccountProxy:getBalance()
return self.balance or 0
end
-- Example usage
local acc_1 = AccountProxy:new()
acc_1:deposit(100.0)
print(acc_1:getBalance()) -- 100.0
acc_1:withdraw(50.0)
print(acc_1:getBalance()) -- 50.0