[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Example of Encapsulation Object Oriented Privacy v. Chapter 16.4 Example
- From: Dustin Juliano <velusdarkbind@...>
- Date: Mon, 9 Feb 2009 09:18:31 -0500
This is a contrast for the example provided in (16.4 - Privacy) of
"Programming in Lua".
The given example from the original text was:
function newAccount (initialBalance)
local self = {balance = initialBalance}
local withdraw = function (v)
self.balance = self.balance - v
end
local deposit = function (v)
self.balance = self.balance + v
end
local getBalance = function () return self.balance end
return {
withdraw = withdraw,
deposit = deposit,
getBalance = getBalance
}
end
This works, but could become cumbersome and obfuscated if you are
making a "class" in a Lua file that has several dozen "member"
functions, "member data", and mixes of "private" and "public."
My suggested version is clearer, but requires you to make a module (a
separate Lua file). This shouldn't be a problem, though.
[bank.lua]
--Bank "class"
P = {}
-- You can declare your class (instantiate it) here, in addition to
this
-- module which defines it. This is optional. See note at end.
-- This will create a global variable in the calling environment.
bank = P
-----------------------------------------
-- "private" member variable declarations
-----------------------------------------
local m_balance = 0
-----------------------------------------
--"public" member function definitions
-----------------------------------------
function P.withdraw(v)
m_balance = m_balance - v
end
function P.deposit(v)
m_balance = m_balance + v
end
function P.getBalance() return m_balance end
--If you omit 'bank = P' from above, this will be absolutely needed
--to use your instantiated "class".
return P
[EOF bank.lua]
To use it, from inside Lua interpreter or another script, load it up.
If you did not declare 'bank = P' just assign the require or dofile
function to a variable and you can access it that way.
m_balance is never accessible from outside the table. If you do a
check, it is not even listed as part of the table; it is fully
encapsulated by those member functions.
Hope this is helpful to anyone looking to do OOP with Lua. I had read
through many examples and in the book and saw a, perhaps, easier way
to accomplish what the example was offering.
Cheers,
D.