[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Seemingly inconsistency between function in a local variable and local function
- From: Jerome Vuarand <jerome.vuarand@...>
- Date: Mon, 2 Apr 2012 14:33:16 +0200
2012/4/2 Robert Klemme <shortcutter@googlemail.com>:
> Hi,
>
> while musing about http://forum.luahub.com/index.php?topic=3559.0 I
> ran across this:
>
> do
> --[[ all these do NOT work
> local f2
> local f2 = nil
> local function f2() end
> --]]
>
> local function f1()
> return f2()
> end
>
> local function f2()
> return 123
> end
>
> function f()
> return f1()
> end
> end
>
> ok, error = pcall(function() print(f()) end)
>
> if ok then
> print('--OK')
> else
> print(error)
> end
>
> do
> -- this works:
> local g2
>
> local function g1()
> return g2()
> end
>
> --[[
> but we cannot do
> local function g2()
>
> only if assigned like this:
> --]]
> g2 = function()
> return 123
> end
>
> function g()
> return g1()
> end
> end
>
> ok, error = pcall(function() print(g()) end)
>
> if ok then
> print('--OK')
> else
> print(error)
> end
>
> Why is that? What did I overlook?
Every time you write the keyword "local", you create/declare a new
local variable, which can shadow another one with the same name. For
example in the following:
local f2
local function f2() return 123 end
there are two local variables named f2, and the first one will always
be nil. So in the following:
local f2
local function f1() return f2() end
local function f2() return 123 end
the f1 function references the first f2 variable. You can either use
your syntax, or you can write it like that:
local f2
local function f1() return f2() end
function f2() return 123 end -- note the absence of local keyword