lua-users home
lua-l archive

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


Hello everybody!

I have tested a privacy design in OO Lua based in PiL, mixing normal classes (16.1) and closure aproach (16.4), with few lines. In pself table, I put private fields and methods. In self are public fields and methods.

It works nice with Module.

Sincerely yours!
Joao Von


--- PrivateAccount.lua ---

--- @module NewAccount

local class = require '30log'
local NewAccount = {}
NewAccount = class('NewAccount')

--- Auxiliary function
local function private (initialValue)
  local value = initialValue
  return {set = function (v) value = v end, get = function () return value end}
end

--- Private fields
local pself ={
   balance = private(),
   client = private(),
   LIM = 10000
}

--- Private method

--- Extra credit
function pself.extra()
   if pself.balance.get() > pself.LIM then
    return pself.balance.get() * 0.10
  else
    return 0
   end
end

--- Public Methods

--- Constructor
function NewAccount.init(self, name, initialBalance)
   pself.balance.set(initialBalance)
   pself.client.set(name)
end

--- Use mutator
function NewAccount.withdraw(self, v)
  pself.balance.set(pself.balance.get() - v)
end

--- Use mutator
function NewAccount.deposit(self, v)
  pself.balance.set(pself.balance.get() + v)
end

--- Accessor method
function NewAccount.getBalance(self)
  return pself.balance.get() + pself.extra()
end

--- Accessor method
function NewAccount.getClient(self)
  return pself.client.get()
end

return NewAccount

--- Privacy.lua ---

local NewAccount = require 'PrivateAccount'

Account = NewAccount:new('John', 15000)
print('Client '..Account:getClient()) 
print('Balance '..Account:getBalance())
Account:withdraw(5000)
print('Client '..Account:getClient()) 
print('Balance '..Account:getBalance())

assert(not pself.balance, 'Balance public!')
assert(not pself.client, 'Client public!')
assert(not pself.extra, 'Extra public!')