lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


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.
this is my code:
-- 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