There is a huge difference between this form…
local someFunction local function otherFunction(x) return someFunction(x + 1) end someFunction = function(x) return x+1 end print(otherFunction(0)) -- this'll work, prints 2
…which uses only “native Lua” calling “native Lua” and will defer the evaluation of “someFunction” within “otherFunction” until actually called, so everything works as expected…
…and THIS form (as per jvmaster77)…
local someListener someDisplayObject:addEventListener("whatever", someListener) someListener = function(event) -- will never be called end
…which attempts to pass a reference to a not-yet-existent function to an internal API routine, so the API gets a nil when expecting a function, so no event is ever gonna fire that function, as the API has no way to know what function you intended to provide itwith (or even if you ever got around to actually defining it AT ALL!)
That is, addEventListener() isn’t passed the “name” of the function to lookup later, it’s passed a reference – but it’s a nil reference to something that doesn’t exist yet, there is no memory address allocated for a function by simply writing “local someListener”. By the time you actually DO define the function and allocate storage for it in the next line, it’s too late, the API will never know about it.
It’s a bit like trying to create a closure around a forward declaration - the two concepts are mutually at odds with each other: you either need the reference as it exists NOW… or not, and instead wish to access whatever that variable references at some time in the future. Sending references to the API is like the closure scenario – it’s gonna pass the value as it exists *right now*.
fwiw, hth