This topic contains 2 replies, has 2 voices, and was last updated by  bceamer 8 years, 11 months ago.

Lua Scope

  • It was mentioned that if local was not part of a declaration, the variable would be global. Is the same true for modules?, is the variable global to the module or wider than that?

    I have a database module that looks like this:

    function connectOracle(vInstance, vUserid, vPassword)
    conn = db.connect{api=db.ORACLE_OCI,name=vInstance,user=vUserid,password=vPassword,live=true }
    return conn
    end

    function getAllUnitLoadTemp()
    rs = conn:query{sql=’SELECT facility,nurse_unit_desc,reg_cnt,regntt_cnt,zz_cnt,regphys_cnt,nttphys_cnt FROM unit_load_temp’}
    –conn:query{sql=”SELECT COLUMN_NAME FROM DBA_TAB_COLUMNS WHERE TABLE_NAME = ‘PERSON'”}
    return rs
    end

    Is conn global to the module or is it visible to the whole script ?

    Hi,
    I found the this tutorial useful when learning lua – Scope Tutorial

    A simple answer however, is that anything not defined as local is global across all modules and functions. Best practice is to use local variables as much as possible. Where you define the variable determines the scope. If you want the variable to be in scope for the module but out of scope for the main routine then define it as local at the top of the module.

    You might also consider the following where all variables are local, even though they are named the same:

    function main(Data)
       local conn = connectOracle('Name', 'User', 'Password')
       local rs = getAllUnitLoadTemp(conn)
    
    end
    
    
    -- put this in the module
    function connectOracle(vInstance, vUserid, vPassword)
       local conn = db.connect{api=db.ORACLE_OCI,name=vInstance,user=vUserid,password=vPassword,live=true }
       return conn
    end
    –
    function getAllUnitLoadTemp(conn)
       local rs = conn:query{sql=’SELECT facility,nurse_unit_desc,reg_cnt,regntt_cnt,zz_cnt,regphys_cnt,nttphys_cnt FROM unit_load_temp’}
       return rs
    end

    By the way, with auto-completion turned on in Translator you can easily check the scope by starting to type the variable name. It will appear in the auto-complete list when it is in scope.

    That’s what I figured. Much like ‘C’

    Thanks

You must be logged in to reply to this topic.