lua-users home
lua-l archive

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

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...)

The problem is that without local declarations, you cannot say where the variable is local to.

Two simple examples:

-- Restrict the scope of a large temporary. Really dumb,
-- but anything real would take more than 3 lines.
  local temp = string.rep(name.." ", 1e7)
-- 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
      error "You cannot deposit a negative amount"
  function self.withdraw(x)
    if x <= balance then
      if x >= 0 then
        -- *** What is the scope of balance --
        balance = balance - x
        error "You cannot withdraw a negative amount"
      error "You do not have enough funds to withdraw that amount"
  function self.balance()
    return balance
  return self