Conditional definitions -Odd results

I am writing a general module to define screen layouts with optional  Tool bars (as one example).

Can anyone explain why the first code example, below, does not give results as expected, but second code example does work, as expected (by me !)?

Thanks.

Here’s the code that fails…

–===================this code creates a nil value variable in module array=======

if _G.ui.ToolBarRequired==true then
     local toolBarHeight =math.floor(display.contentHeight*0.1)
                print ( “local set=”,toolBarHeight )_— prints value as calculated _
else
     local toolBarHeight =0
end

ScreenLayOutlocals.toolBarHeight=toolBarHeight— for external references

print ( ScreenLayOutlocals.toolBarHeight )_— prints value as nil _

–============ _This code works and places value in module arra_y===========

local toolBarHeight

if _G.ui.ToolBarRequired==true then
      toolBarHeight =math.floor(display.contentHeight*0.1)
                print ( “local set=”,toolBarHeight )_— prints value as calculated _
else
      toolBarHeight =0
end

ScreenLayOutlocals.toolBarHeight=toolBarHeight

print ( ScreenLayOutlocals.toolBarHeight )_— prints value as calculated _

–================

That’s because in the first example toolbarHeight is declared local within the “if” block. As soon as the if block goes out of scope (end) the variable ceases to exist. In the second example it’s declared local to the module.

Thanks.

Old habits-die hard!

I am used to scope in other languages being at procedure level, not at code structure block level… :wacko:

I must forget all those old procedural coding rules,  and get more modern! :wink:

That’s because in the first example toolbarHeight is declared local within the “if” block. As soon as the if block goes out of scope (end) the variable ceases to exist. In the second example it’s declared local to the module.

Thanks.

Old habits-die hard!

I am used to scope in other languages being at procedure level, not at code structure block level… :wacko:

I must forget all those old procedural coding rules,  and get more modern! :wink: