Global Variable Question

If I define a variable as local in forward declarations do I also need to set it as a local variable in Scene Create in order for it not to be a global variable?   In otherwords, if I set it up as in Example 2 below would that make rock a global variable since local is not in front of rock in Scene Create?

Example 1:

Forward Declarations

local rock

SCENE CREATE

local rock = display.newImage(“rock.png”)


Example 2:

Forward Declarations

local rock

SCENE CREATE

rock = display.newImage(“rock.png”)

Thanks

Lori

Hi Lori,

If you declare a local variable inside a function, it will be unique to that function, even if you’ve named it the same as a variable that you forward declared. Then, when the function ends, that variable will be considered “finished” and it will be garbage-collected.

So, in your Example 1, the “rock” that you forward declare will be unique versus the one that you create inside the function (scene create function). But in your Example 2, this will be the same variable reference, because inside the function, you’re referencing the forward-declared variable from above.

Here’s another code example to illustrate it… just run this and see how the two Lua references are unique:

[lua]

local rock

local function checkRef()

   local rock = display.newRect( 100,0,10,10 )

   print( “rock inside function”, rock )

end

checkRef()

rock = display.newRect( 0,0,10,10 )

print( “rock outside function”, rock )

[/lua]

Brent

Thanks!

This is one of those things that drives you crazy when you don’t realise you have 2 variables with the same name, and one of them isn’t behaving as you expect it to  :slight_smile:

Hi Lori,

If you declare a local variable inside a function, it will be unique to that function, even if you’ve named it the same as a variable that you forward declared. Then, when the function ends, that variable will be considered “finished” and it will be garbage-collected.

So, in your Example 1, the “rock” that you forward declare will be unique versus the one that you create inside the function (scene create function). But in your Example 2, this will be the same variable reference, because inside the function, you’re referencing the forward-declared variable from above.

Here’s another code example to illustrate it… just run this and see how the two Lua references are unique:

[lua]

local rock

local function checkRef()

   local rock = display.newRect( 100,0,10,10 )

   print( “rock inside function”, rock )

end

checkRef()

rock = display.newRect( 0,0,10,10 )

print( “rock outside function”, rock )

[/lua]

Brent

Thanks!

This is one of those things that drives you crazy when you don’t realise you have 2 variables with the same name, and one of them isn’t behaving as you expect it to  :slight_smile: