understanding function

can someone tell me what is wrong with this code. basically if i write them like below it works. 

local function printMyName(arg) print(arg) end local answer = 'Kenny is kool!' printMyName(answer)

but if i write them like this it crash saying that attempt to call global printMyName( a nil value)

local printMyName

local answer = ‘Kenny is kool!’

printMyName(answer)

 function printMyName(arg)

print(arg)

end

–im trying to keep my function below but it won’t work

This

local printMyName local answer = 'Kenny is kool!' printMyName(answer) function printMyName(arg) print(arg) end

should be this:

local printMyName -- You are declaring a local variable named printMyName -- At this point, 'printMyName' contains nothing ... local answer = 'Kenny is kool!' -- printMyName(answer) -- Not defined yet. This will fail printMyName = function(arg) -- The way you had it created a global named printMyName print(arg) end -- At this point, 'printMyName' contains a reference to a function -- Now, and only now can you call that function using the reference in the local... printMyName(answer)

I know you want to have the line calling to the function higher in the file than the definition, but due to scope and visibility rules, you cannot.

However, if you had something like this it would work:

myMod.lua

local mod = {} -- -- Local data -- local answer = 'Kenny is kool!' -- -- Local Function Declaration(s) -- local printMyName -- -- Module function definition(s) -- function mod.doit( ) printMyName( answer ) end -- -- Local function definitions(s) -- printMyName = function( arg ) print(arg) end return mod

main.lua

local myMod = require "myMod" -- At this point, file is loaded and interpreted. -- During interpretation, the local function in myMod.lua has been declared, then defined -- So, now if we call the module function doit(), that function will be able to use the local -- variable printMyName and reference the function it points to. myMod.doit()

The example I posted above is similar to what you are allowed to do when writing composer scene files.  You simply have to keep in mind:

  • Scope and Visibility Rules
  • Order Of Operation rules

At the end of the day, just remember.  It is IMPOSSIBLE to call a function before it is defined.

your last post make sense now. thanks a lot