Local v Global Variables

Help creating logic scripts for Air Manager Instruments

Moderators: russ, Ralph

Post Reply
Message
Author
tomlithgow
Posts: 60
Joined: Sun Jun 12, 2016 3:11 pm

Local v Global Variables

#1 Post by tomlithgow »

When I started doing a fair bit of Lua programming in AM, I decided to get the Lua "Bible".."Programming in Lua" by Roberto Ierusalemimschy. I've read through it and thought I understood the use of local variables, but the usage I see in AM seems the reverse of what I'm reading.
First; by default, variables are global (there is no explicit global declaration) and therefore available everywhere in a piece of code.
Second; local variable declared as such within a function or block are local to that function/block and are inaccessible out with the function/block.

Why then does it seem to be normal to declare variables that you would want to be generally available throughout a piece of code as local?

User avatar
Corjan
Posts: 2941
Joined: Thu Nov 19, 2015 9:04 am

Re: Local v Global Variables

#2 Post by Corjan »

Hi,

You are right in that you should declare a variable local if you only want to use the variable in that context (function, if statement etc.).
In practice though, since instrument scripts tend to be very small, it doesn't really make a difference one way or the other.

Corjan

tomlithgow
Posts: 60
Joined: Sun Jun 12, 2016 3:11 pm

Re: Local v Global Variables

#3 Post by tomlithgow »

I thought that was the case...but I also think I read somewhere that by limiting the scope of variables with local declarations made for more efficient processing and makes better use of memory. But as you say, in general, instrument code is not extensive.
That said, some time ago I was trying to write a script for a Bendix King KLN94 instrument which had multiple view options and ran to 12 pages of code.

Post Reply