|
|
||
|
On 3-Oct-06, at 11:14 AM, Javier Guerra wrote:
On Tuesday 03 October 2006 9:49 am, David Olofson wrote:I wasn't really aware of this issue at first (haven't designed all that many languages before), and of course, got it wrong in EEL (local by default), did some scripting, realized it was just plain stupid, switched to explicit declarations for everything, and never looked back.
i've read (and agree with) the long and theoretical explanations about why
local by default is the wrong choice; but could you share any short anecdote
that convinced you of this?
my point is that a short and simple example might be more convincing than
the 'real' reasons (and easier to repeat again and again each time this issue
is mentioned...)
Two simple examples:
-- Restrict the scope of a large temporary. Really dumb, -- but anything real would take more than 3 lines. do local temp = string.rep(name.." ", 1e7) f:write(md5(temp)) end -- temp is now gone.
-- Example 2: private closed variables
-- Note the lines with *** (doesn't work with "local-by-default")
function bankAccount()
local balance = 0
local self = {}
function self.deposit(x)
if x >= 0 then
-- *** What is the scope of balance --
balance = balance + x
else
error "You cannot deposit a negative amount"
end
end
function self.withdraw(x)
if x <= balance then
if x >= 0 then
-- *** What is the scope of balance --
balance = balance - x
else
error "You cannot withdraw a negative amount"
end
else
error "You do not have enough funds to withdraw that amount"
end
end
function self.balance()
return balance
end
return self
end