Usina BRAdvPL Guide
Sign in
← CatalogFOUNDATION

Variable
scope

Scope determines where a variable can be accessed and how long its value remains available during execution.

EXPLICIT DECLARATION
Local nNumero := 10

The identifier states that nNumero belongs to the function local scope.

SCOPEVISIBILITYLIFETIME
LOCALOnly the declaring routineUntil the function returnsSTATICDepends on declaration locationWhile the environment is runningPRIVATEDynamic scopeUntil the creating function returnsPUBLICGlobal, unless hidden by a PrivateUntil execution ends
01

LOCAL

Current function

Created on each function activation. Recursive calls receive independent sets of local variables.

Visibility
Only the declaring routine
Lifetime
Until the function returns
EXAMPLE
User Function Pai()
    Local nVar := 10
    Filha()
Return .T.

Static Function Filha()
    // nVar is not visible here
Return
02

STATIC

Routine or file

Inside a function, it remains restricted to that routine and retains its value between calls. Outside routines, it can be accessed in the current source file.

Visibility
Depends on declaration location
Lifetime
While the environment is running
EXAMPLE
User Function Contador()
    Static nChamadas := 0
    nChamadas++
    ConOut(nChamadas)
Return
03

PRIVATE

Creating function and descendant calls

It may be declared or created implicitly by assignment. A Private with the same name in a called function temporarily hides the previous one.

Visibility
Dynamic scope
Lifetime
Until the creating function returns
EXAMPLE
User Function Pai()
    Private nVar := 10
    Filha()
Return .T.

Static Function Filha()
    ConOut(nVar) // 10
Return
04

PUBLIC

Entire environment

Remains available after the creating function returns. Without explicit initialization, its value is logical false (.F.).

Visibility
Global, unless hidden by a Private
Lifetime
Until execution ends
EXAMPLE
User Function CriarStatus()
    Public lSistemaAtivo := .T.
Return

User Function ConsultarStatus()
    ConOut(lSistemaAtivo)
Return
BEST PRACTICE

Declare your intent

Prefer `LOCAL` for temporary data and `STATIC` when state truly needs to be retained. Use `PRIVATE` and `PUBLIC` only when dynamic or global visibility is part of the routine design.

REFERENCES
  1. SILVA, Waterloo Ferreira da. A Linguagem AdvPL. 2004, p. 22-24. Content summarized and reviewed; examples adapted.
  2. TOTVS. Variable Context within a Program. TDN.
  3. TOTVS. Creating and Assigning Variables. TDN.
  4. TOTVS. Microsiga Protheus SDK. TDN — additional reference.