lua-users home
lua-l archive

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

Eva Schmidt writes:
> I wondered if it would also be an optimisation to define functions in a single 
> Lua script also as local everytime? Does this make any sense?

Defining functions as local not only can provide a small performance increase
but also--more significantly I maintain--allows improved privacy and better
static checking of undefined variables via the "luac -p -l" trick[1].

The lexical scoping of locals does require predeclaration and sometimes makes
the code only slightly more awkward than otherwise:

  local b         -- Predeclare.
  local function a(n)
    if n == 0 then return end
    print 'even'; b(n-1)
  function b(n)   -- This is a local that only looks like a global.
    print 'odd'; a(n-1)

It also makes code immune to changes to those variables because it is a type of

    local print = print
    function test(n) print(n^2) end
  print = my_print  -- redefine print
  test(2) -- uses original print.