This topic contains 1 reply, has 2 voices, and was last updated by  Jonathan Marshall 1 year, 9 months ago.

Local v. Global variable usage

  • I’ve recently had an exchange through support tickets with iNTERFACEWARE regarding issues whose root causes were ultimately tracked to my incomplete understanding of how global variables behaved, and I am still not 100% clear how I’m supposed to account for some of the behaviors. I am pursuing a better understanding, but in the meantime, I do have a specific question, revolving around a code formation as below:

    if Lookup(value) then
    FlagYes = 1
    if Lookup2(value) then
    local FlagYes2 = 1
    trace(FlagYes, FlagYes2)

    From my experiment with my interface, assuming the value of both Lookups was ‘true’, then the trace() command would show FlagYes as ‘1’, while Flagyes2 would be ‘0’. My understanding was that if I declare a local variable inside an if statement or a function, that variable’s value will only be present within that if statement or function. I can’t reference FlagYes2, for example, in a subfunction and expect it to be ‘1, because it is a local variable confined to that second if statement. How would I accomplish my requirement (being able to set a flag with an if statement) without using a global variable?

    -Robert James,
    Interface Analyst,
    GetWellNetwork, Inc.

    Hi Robert,

    Any control structure in Lua creates a scope, so

    if true then
      local x = true
    trace(x) // returns nil

    x is nil when traced because the x in the if block ceases to exist when the block ends. In order for it to persist when using the local keyword, it must be declared within the scope/block in which you want to use it, such as

    local x
    if true then
      x = true
    trace(x) // returns true

You must be logged in to reply to this topic.