advpl-specialist
Referencia

Funcoes Nativas

Referencia rapida das funcoes nativas ADVPL/TLPP mais utilizadas no TOTVS Protheus

Protheus Native Functions Reference

Quick reference for the most commonly used ADVPL/TLPP native functions in TOTVS Protheus.


String Functions

Alltrim

Removes leading and trailing spaces from a string.

Syntax: Alltrim( cString ) --> cTrimmed

ParamTypeDescription
cStringCString to trim

Return: C - String without leading or trailing spaces.

Example:

Local cName := "  John Doe  "
cName := Alltrim(cName) // "John Doe"

SubStr

Extracts a substring from a string starting at a given position.

Syntax: SubStr( cString, nStart [, nCount] ) --> cSubString

ParamTypeDescription
cStringCSource string
nStartNStarting position (1-based)
nCountNNumber of characters to extract (optional, defaults to rest of string)

Return: C - Extracted substring.

Example:

Local cText := "ADVPL Language"
Local cSub  := SubStr(cText, 1, 5) // "ADVPL"
Local cRest := SubStr(cText, 7)    // "Language"

StrTran

Replaces all occurrences of a substring within a string.

Syntax: StrTran( cString, cSearch [, cReplace [, nStart [, nCount]]] ) --> cResult

ParamTypeDescription
cStringCSource string
cSearchCSubstring to find
cReplaceCReplacement string (default: empty string)
nStartNFirst occurrence to replace (default: 1)
nCountNNumber of occurrences to replace (default: all)

Return: C - String with replacements applied.

Example:

Local cText := "Hello World"
Local cCPF  := ""

cText := StrTran(cText, "World", "Protheus") // "Hello Protheus"
// Remove characters
cCPF := StrTran("123.456.789-00", ".", "")
cCPF := StrTran(cCPF, "-", "") // "12345678900"

PadR

Pads a value with trailing characters (default: spaces) to a specified length.

Syntax: PadR( xValue, nLength [, cFillChar] ) --> cPadded

ParamTypeDescription
xValueUValue to pad (converted to string)
nLengthNTotal desired length
cFillCharCFill character (default: space)

Return: C - Right-padded string.

Example:

Local cCode := PadR("001", 6)        // "001   "
Local cFill := PadR("ABC", 6, "0")   // "ABC000"

PadL

Pads a value with leading characters (default: spaces) to a specified length.

Syntax: PadL( xValue, nLength [, cFillChar] ) --> cPadded

ParamTypeDescription
xValueUValue to pad (converted to string)
nLengthNTotal desired length
cFillCharCFill character (default: space)

Return: C - Left-padded string.

Example:

Local cNum := PadL("42", 6)        // "    42"
Local cZero := PadL("42", 6, "0")  // "000042"

PadC

Centers a value within a string of the specified length.

Syntax: PadC( xValue, nLength [, cFillChar] ) --> cPadded

ParamTypeDescription
xValueUValue to center (converted to string)
nLengthNTotal desired length
cFillCharCFill character (default: space)

Return: C - Center-padded string.

Example:

Local cTitle := PadC("REPORT", 20) // "       REPORT       "

Upper

Converts all characters in a string to uppercase.

Syntax: Upper( cString ) --> cUpper

ParamTypeDescription
cStringCString to convert

Return: C - Uppercase string.

Example:

Local cName := Upper("protheus") // "PROTHEUS"

Lower

Converts all characters in a string to lowercase.

Syntax: Lower( cString ) --> cLower

ParamTypeDescription
cStringCString to convert

Return: C - Lowercase string.

Example:

Local cName := Lower("PROTHEUS") // "protheus"

Len

Returns the length of a string or array.

Syntax: Len( xValue ) --> nLength

ParamTypeDescription
xValueC/AString or array

Return: N - Number of characters in string or elements in array.

Example:

Local nLen := Len("ADVPL")  // 5
Local aArr := {1, 2, 3}
nLen := Len(aArr)            // 3

At

Returns the position of the first occurrence of a substring within a string.

Syntax: At( cSearch, cTarget [, nStart] ) --> nPosition

ParamTypeDescription
cSearchCSubstring to find
cTargetCString to search in
nStartNStarting position for search (default: 1)

Return: N - Position of first occurrence, or 0 if not found.

Example:

Local nPos := At("World", "Hello World") // 7
Local nPos2 := At("xyz", "Hello World")  // 0

Rat

Returns the position of the last occurrence of a substring within a string.

Syntax: Rat( cSearch, cTarget ) --> nPosition

ParamTypeDescription
cSearchCSubstring to find
cTargetCString to search in

Return: N - Position of last occurrence, or 0 if not found.

Example:

Local cPath := "C:\TOTVS\bin\appserver.exe"
Local nPos := Rat("\", cPath) // Position of last backslash
Local cFile := SubStr(cPath, nPos + 1) // "appserver.exe"

Stuff

Deletes and/or inserts characters in a string at a specified position.

Syntax: Stuff( cString, nStart, nDelete, cInsert ) --> cResult

ParamTypeDescription
cStringCSource string
nStartNStarting position
nDeleteNNumber of characters to delete
cInsertCString to insert

Return: C - Modified string.

Example:

Local cText := "Hello World"
cText := Stuff(cText, 6, 1, " Beautiful ") // "Hello Beautiful World"
// Replace portion
cText := Stuff("ABCDEF", 3, 2, "XY") // "ABXYEF"

Left

Returns a specified number of characters from the left side of a string.

Syntax: Left( cString, nCount ) --> cResult

ParamTypeDescription
cStringCSource string
nCountNNumber of characters to return

Return: C - Leftmost characters.

Example:

Local cBranch := Left("01001", 2) // "01"

Returns a specified number of characters from the right side of a string.

Syntax: Right( cString, nCount ) --> cResult

ParamTypeDescription
cStringCSource string
nCountNNumber of characters to return

Return: C - Rightmost characters.

Example:

Local cExt := Right("report.pdf", 3) // "pdf"

Replicate

Returns a string repeated a specified number of times.

Syntax: Replicate( cString, nTimes ) --> cResult

ParamTypeDescription
cStringCString to repeat
nTimesNNumber of repetitions

Return: C - Repeated string.

Example:

Local cLine := Replicate("-", 40) // "----------------------------------------"

Space

Returns a string of spaces of the specified length.

Syntax: Space( nCount ) --> cSpaces

ParamTypeDescription
nCountNNumber of spaces

Return: C - String of spaces.

Example:

Local cField := Space(30) // Initializes a 30-character empty field

Transform

Formats a value according to a picture mask.

Syntax: Transform( xValue, cPicture ) --> cFormatted

ParamTypeDescription
xValueUValue to format
cPictureCPicture/mask string

Return: C - Formatted string.

Example:

Local cVal := Transform(1234.56, "@E 999,999.99")  // "  1.234,56"
Local cCPF := Transform("12345678900", "@R 999.999.999-99") // "123.456.789-00"

StrZero

Converts a number to a string with leading zeros.

Syntax: StrZero( nValue, nLength [, nDecimals] ) --> cResult

ParamTypeDescription
nValueNNumeric value
nLengthNTotal string length
nDecimalsNNumber of decimal places (default: 0)

Return: C - Zero-padded numeric string.

Example:

Local cNum := StrZero(42, 6)   // "000042"
Local cDec := StrZero(3.5, 8, 2) // "00003.50"

CharRem

Removes specified characters from a string.

Syntax: CharRem( cCharsToRemove, cString ) --> cResult

ParamTypeDescription
cCharsToRemoveCCharacters to remove
cStringCSource string

Return: C - String with specified characters removed.

Example:

Local cClean := CharRem(".-/", "123.456.789-00") // "12345678900"

Asc

Returns the ASCII code of the first character of a string.

Syntax: Asc( cChar ) --> nAsciiCode

ParamTypeDescription
cCharCCharacter string

Return: N - ASCII code of the first character.

Example:

Local nCode := Asc("A") // 65
Local nCode2 := Asc("0") // 48

Chr

Returns the character corresponding to an ASCII code.

Syntax: Chr( nAsciiCode ) --> cChar

ParamTypeDescription
nAsciiCodeNASCII code (0-255)

Return: C - Character for the given ASCII code.

Example:

Local cChar := Chr(65)  // "A"
Local cCRLF := Chr(13) + Chr(10) // Carriage return + line feed

Date/Time Functions

Date

Returns the current system date.

Syntax: Date() --> dToday

Return: D - Current system date.

Example:

Local dToday := Date()
Conout("Today is: " + DtoC(dToday))

dDataBase

Gets or sets the Protheus base date (reference date used in operations).

Syntax: dDataBase --> dDate (read) / dDataBase := dDate (write)

Return: D - Current base date.

Example:

// Get current database date
Local dRef := dDataBase

// Set base date
dDataBase := CtoD("01/01/2026")

DtoS

Converts a date to a string in the format YYYYMMDD.

Syntax: DtoS( dDate ) --> cDateString

ParamTypeDescription
dDateDDate value

Return: C - Date string in YYYYMMDD format.

Example:

Local cDate := DtoS(Date()) // "20260304"

StoD

Converts a string in YYYYMMDD format to a date value.

Syntax: StoD( cDateString ) --> dDate

ParamTypeDescription
cDateStringCDate string in YYYYMMDD format

Return: D - Date value.

Example:

Local dDate := StoD("20260304") // 2026-03-04

CtoD

Converts a string to a date using the current date format.

Syntax: CtoD( cDate ) --> dDate

ParamTypeDescription
cDateCDate string in current system format (e.g., DD/MM/YYYY)

Return: D - Date value.

Example:

Local dDate := CtoD("04/03/2026") // March 4, 2026 (DD/MM/YYYY)

DtoC

Converts a date to a character string using the current date format.

Syntax: DtoC( dDate ) --> cDate

ParamTypeDescription
dDateDDate value

Return: C - Date string in the current system format.

Example:

Local cDate := DtoC(Date()) // "04/03/2026" (in DD/MM/YYYY format)

Day

Returns the day of the month from a date.

Syntax: Day( dDate ) --> nDay

ParamTypeDescription
dDateDDate value

Return: N - Day of the month (1-31).

Example:

Local nDay := Day(Date()) // 4 (for March 4)

Month

Returns the month number from a date.

Syntax: Month( dDate ) --> nMonth

ParamTypeDescription
dDateDDate value

Return: N - Month number (1-12).

Example:

Local nMonth := Month(Date()) // 3 (for March)

Year

Returns the year from a date.

Syntax: Year( dDate ) --> nYear

ParamTypeDescription
dDateDDate value

Return: N - Four-digit year.

Example:

Local nYear := Year(Date()) // 2026

DOW

Returns the day of the week as a number.

Syntax: DOW( dDate ) --> nDayOfWeek

ParamTypeDescription
dDateDDate value

Return: N - Day of week (1=Sunday, 2=Monday, ..., 7=Saturday).

Example:

Local nDow := DOW(Date())
If nDow == 1 .Or. nDow == 7
    Conout("Weekend!")
EndIf

Time

Returns the current system time as a string.

Syntax: Time() --> cTime

Return: C - Time string in HH:MM:SS format.

Example:

Local cTime := Time() // "14:30:45"

ElapTime

Calculates the elapsed time between two time strings.

Syntax: ElapTime( cStartTime, cEndTime ) --> cElapsed

ParamTypeDescription
cStartTimeCStart time in HH:MM:SS format
cEndTimeCEnd time in HH:MM:SS format

Return: C - Elapsed time in HH:MM:SS format.

Example:

Local cStart := "08:00:00"
Local cEnd   := "17:30:00"
Local cElap  := ElapTime(cStart, cEnd) // "09:30:00"

DaySub

Subtracts a number of days from a date.

Syntax: DaySub( dDate, nDays ) --> dResult

ParamTypeDescription
dDateDBase date
nDaysNNumber of days to subtract

Return: D - Resulting date.

Example:

Local dYesterday := DaySub(Date(), 1)
Local dLastWeek  := DaySub(Date(), 7)

MonthSub

Subtracts a number of months from a date.

Syntax: MonthSub( dDate, nMonths ) --> dResult

ParamTypeDescription
dDateDBase date
nMonthsNNumber of months to subtract

Return: D - Resulting date.

Example:

Local dLastMonth := MonthSub(Date(), 1)
Local dLastYear  := MonthSub(Date(), 12)

DateValid

Validates whether a date is valid.

Syntax: DateValid( cDate ) --> lValid

ParamTypeDescription
cDateCDate string in current system format

Return: L - .T. if the date is valid, .F. otherwise.

Example:

If DateValid("29/02/2026")
    Conout("Valid date")
Else
    Conout("Invalid date") // 2026 is not a leap year
EndIf

Numeric Functions

Int

Returns the integer portion of a numeric value.

Syntax: Int( nValue ) --> nInteger

ParamTypeDescription
nValueNNumeric value

Return: N - Integer portion (truncated, not rounded).

Example:

Local nInt := Int(3.7)  // 3
Local nNeg := Int(-3.7) // -3

Round

Rounds a numeric value to a specified number of decimal places.

Syntax: Round( nValue, nDecimals ) --> nRounded

ParamTypeDescription
nValueNValue to round
nDecimalsNNumber of decimal places

Return: N - Rounded value.

Example:

Local nVal := Round(3.456, 2)  // 3.46
Local nVal2 := Round(3.454, 2) // 3.45

Abs

Returns the absolute value of a number.

Syntax: Abs( nValue ) --> nAbsolute

ParamTypeDescription
nValueNNumeric value

Return: N - Absolute value.

Example:

Local nAbs := Abs(-42) // 42
Local nAbs2 := Abs(42) // 42

Val

Converts a character string to a numeric value.

Syntax: Val( cString ) --> nValue

ParamTypeDescription
cStringCString containing a numeric value

Return: N - Numeric value.

Example:

Local nVal := Val("123.45") // 123.45
Local nVal2 := Val("42")    // 42

Str

Converts a numeric value to a character string.

Syntax: Str( nValue [, nLength [, nDecimals]] ) --> cString

ParamTypeDescription
nValueNNumeric value
nLengthNTotal string length (default: 10)
nDecimalsNNumber of decimal places (default: 0)

Return: C - String representation of the number.

Example:

Local cNum := Str(42)        // "        42"
Local cDec := Str(3.14, 6, 2) // "  3.14"

NoRound

Truncates a numeric value to a specified number of decimal places without rounding.

Syntax: NoRound( nValue, nDecimals ) --> nTruncated

ParamTypeDescription
nValueNValue to truncate
nDecimalsNNumber of decimal places

Return: N - Truncated value.

Example:

Local nVal := NoRound(3.456, 2) // 3.45 (not 3.46)
Local nVal2 := NoRound(9.999, 2) // 9.99

Mod

Returns the remainder of a division (modulo).

Syntax: Mod( nDividend, nDivisor ) --> nRemainder

ParamTypeDescription
nDividendNDividend
nDivisorNDivisor

Return: N - Remainder of the division.

Example:

Local nRem := Mod(10, 3) // 1
Local nEven := Mod(4, 2) // 0 (even number)

Log

Returns the natural logarithm (base e) of a number.

Syntax: Log( nValue ) --> nLog

ParamTypeDescription
nValueNPositive numeric value

Return: N - Natural logarithm.

Example:

Local nLog := Log(2.718281828) // ~1.0

Sqrt

Returns the square root of a number.

Syntax: Sqrt( nValue ) --> nSquareRoot

ParamTypeDescription
nValueNNon-negative numeric value

Return: N - Square root.

Example:

Local nSqrt := Sqrt(16) // 4
Local nSqrt2 := Sqrt(2) // 1.4142...

Max

Returns the larger of two numeric values.

Syntax: Max( nValue1, nValue2 ) --> nMax

ParamTypeDescription
nValue1NFirst value
nValue2NSecond value

Return: N - The larger value.

Example:

Local nMax := Max(10, 20) // 20

Min

Returns the smaller of two numeric values.

Syntax: Min( nValue1, nValue2 ) --> nMin

ParamTypeDescription
nValue1NFirst value
nValue2NSecond value

Return: N - The smaller value.

Example:

Local nMin := Min(10, 20) // 10

Array Functions

aAdd

Adds a new element to the end of an array.

Syntax: aAdd( aArray, xValue ) --> xValue

ParamTypeDescription
aArrayATarget array
xValueUValue to add

Return: U - The value added.

Example:

Local aList := {}
aAdd(aList, "Item 1")
aAdd(aList, "Item 2")
// aList == {"Item 1", "Item 2"}

aDel

Deletes an element from an array at a specified position. Does not resize the array.

Syntax: aDel( aArray, nPosition ) --> aArray

ParamTypeDescription
aArrayATarget array
nPositionNPosition of element to delete

Return: A - The modified array (last element becomes NIL).

Example:

Local aList := {"A", "B", "C", "D"}
aDel(aList, 2)
// aList == {"A", "C", "D", NIL}
aSize(aList, 3) // Resize to remove NIL
// aList == {"A", "C", "D"}

aSize

Resizes an array to the specified number of elements.

Syntax: aSize( aArray, nNewSize ) --> aArray

ParamTypeDescription
aArrayATarget array
nNewSizeNNew array size

Return: A - The resized array.

Example:

Local aList := {"A", "B", "C"}
aSize(aList, 5)  // aList == {"A", "B", "C", NIL, NIL}
aSize(aList, 2)  // aList == {"A", "B"}

aScan

Searches for a value in an array and returns its position.

Syntax: aScan( aArray, xSearch [, nStart [, nCount]] ) --> nPosition

ParamTypeDescription
aArrayAArray to search
xSearchU/BValue to find or code block for comparison
nStartNStarting position (default: 1)
nCountNNumber of elements to search (default: all)

Return: N - Position of the element, or 0 if not found.

Example:

Local aList := {"Apple", "Banana", "Cherry"}
Local nPos := aScan(aList, "Banana") // 2

// Using code block
Local aNums := {10, 25, 30, 45}
nPos := aScan(aNums, {|x| x > 20}) // 2 (first element > 20)

aSort

Sorts an array in ascending order.

Syntax: aSort( aArray [, nStart [, nCount [, bOrder]]] ) --> aArray

ParamTypeDescription
aArrayAArray to sort
nStartNStarting position (default: 1)
nCountNNumber of elements (default: all)
bOrderBCode block for custom ordering

Return: A - The sorted array.

Example:

Local aList := {"Cherry", "Apple", "Banana"}
Local aNums := {3, 1, 4, 1, 5}

aSort(aList) // {"Apple", "Banana", "Cherry"}

// Descending order
aSort(aNums,,, {|x, y| x > y}) // {5, 4, 3, 1, 1}

aClone

Creates a deep copy of an array.

Syntax: aClone( aSource ) --> aNewArray

ParamTypeDescription
aSourceAArray to clone

Return: A - New independent copy of the array.

Example:

Local aOrig := {"A", "B", "C"}
Local aCopy := aClone(aOrig)
aCopy[1] := "X"
// aOrig[1] is still "A"

Array

Creates a new array with a specified number of elements initialized to NIL.

Syntax: Array( nElements [, nElements2, ...] ) --> aArray

ParamTypeDescription
nElementsNNumber of elements in each dimension

Return: A - New array.

Example:

Local aList := Array(5)       // {NIL, NIL, NIL, NIL, NIL}
Local aMatrix := Array(3, 2)  // 3x2 multidimensional array

aFill

Fills array elements with a specified value.

Syntax: aFill( aArray, xValue [, nStart [, nCount]] ) --> aArray

ParamTypeDescription
aArrayATarget array
xValueUValue to fill with
nStartNStarting position (default: 1)
nCountNNumber of elements to fill (default: all)

Return: A - The filled array.

Example:

Local aList := Array(5)
aFill(aList, 0) // {0, 0, 0, 0, 0}

aCopy

Copies elements from one array to another.

Syntax: aCopy( aSource, aTarget [, nStart [, nCount [, nTargetStart]]] ) --> aTarget

ParamTypeDescription
aSourceASource array
aTargetATarget array
nStartNStart position in source (default: 1)
nCountNNumber of elements (default: all)
nTargetStartNStart position in target (default: 1)

Return: A - The target array.

Example:

Local aSource := {1, 2, 3, 4, 5}
Local aTarget := Array(3)
aCopy(aSource, aTarget, 2, 3) // aTarget == {2, 3, 4}

aEval

Evaluates a code block for each element in an array.

Syntax: aEval( aArray, bBlock [, nStart [, nCount]] ) --> aArray

ParamTypeDescription
aArrayAArray to iterate
bBlockBCode block receiving element and index: {|xVal, nIdx| ... }
nStartNStarting position (default: 1)
nCountNNumber of elements (default: all)

Return: A - The original array.

Example:

Local aNames := {"Alice", "Bob", "Charlie"}
aEval(aNames, {|cName, nIdx| Conout(Str(nIdx) + ": " + cName)})

aTail

Returns the last element of an array.

Syntax: aTail( aArray ) --> xValue

ParamTypeDescription
aArrayASource array

Return: U - The last element.

Example:

Local aList := {"First", "Second", "Last"}
Local cLast := aTail(aList) // "Last"

aIns

Inserts a NIL element at a specified position, shifting elements down.

Syntax: aIns( aArray, nPosition ) --> aArray

ParamTypeDescription
aArrayATarget array
nPositionNPosition for insertion

Return: A - The modified array (last element is lost).

Example:

Local aList := {"A", "B", "C", "D"}
aIns(aList, 2)
// aList == {"A", NIL, "B", "C"} - "D" is lost
aList[2] := "X"
// aList == {"A", "X", "B", "C"}

Database Functions

DbSelectArea

Selects a work area by alias name or number.

Syntax: DbSelectArea( xArea ) --> NIL

ParamTypeDescription
xAreaC/NAlias name (string) or work area number

Return: NIL

Example:

DbSelectArea("SA1")
DbSetOrder(1)
DbGoTop()

DbSetOrder

Sets the active index order for the current work area.

Syntax: DbSetOrder( nOrder ) --> NIL

ParamTypeDescription
nOrderNIndex order number

Return: NIL

Example:

DbSelectArea("SA1")
DbSetOrder(1) // Primary index: A1_FILIAL + A1_COD + A1_LOJA

DbSeek

Seeks a record by key in the current index order.

Syntax: DbSeek( xKey [, lSoftSeek [, lLast]] ) --> lFound

ParamTypeDescription
xKeyUKey value to search for
lSoftSeekLIf .T., positions on next key if exact match not found (default: .F.)
lLastLIf .T., seeks the last matching record (default: .F.)

Return: L - .T. if record found, .F. otherwise.

Example:

DbSelectArea("SA1")
DbSetOrder(1)
If DbSeek(xFilial("SA1") + "000001" + "01")
    Conout("Customer found: " + SA1->A1_NOME)
Else
    Conout("Customer not found")
EndIf

DbSkip

Moves the record pointer forward or backward.

Syntax: DbSkip( [nRecords] ) --> NIL

ParamTypeDescription
nRecordsNNumber of records to skip (default: 1, negative to go backward)

Return: NIL

Example:

DbSelectArea("SA1")
DbGoTop()
While !Eof()
    Conout(SA1->A1_NOME)
    DbSkip()
EndDo

DbGoTop

Moves the record pointer to the first record in the current work area.

Syntax: DbGoTop() --> NIL

Return: NIL

Example:

DbSelectArea("SA1")
DbSetOrder(1)
DbGoTop()

DbGoBottom

Moves the record pointer to the last record in the current work area.

Syntax: DbGoBottom() --> NIL

Return: NIL

Example:

DbSelectArea("SA1")
DbGoBottom()
Conout("Last record: " + Str(RecNo()))

RecLock

Locks the current record or adds a new record.

Syntax: RecLock( cAlias, lNewRecord ) --> lSuccess

ParamTypeDescription
cAliasCAlias of the work area
lNewRecordL.T. to add a new record, .F. to lock existing record

Return: L - .T. if lock was successful.

Example:

// Update existing record
DbSelectArea("SA1")
DbSetOrder(1)
If DbSeek(xFilial("SA1") + "000001" + "01")
    If RecLock("SA1", .F.)
        SA1->A1_NOME := "New Name"
        MsUnlock()
    EndIf
EndIf

// Add new record
If RecLock("SA1", .T.)
    SA1->A1_FILIAL := xFilial("SA1")
    SA1->A1_COD    := "000100"
    SA1->A1_LOJA   := "01"
    SA1->A1_NOME   := "New Customer"
    MsUnlock()
EndIf

MsUnlock

Unlocks the current record after RecLock.

Syntax: MsUnlock() --> NIL

Return: NIL

Example:

If RecLock("SA1", .F.)
    SA1->A1_NOME := "Updated Name"
    MsUnlock()
EndIf

RecNo

Returns the current record number.

Syntax: RecNo() --> nRecNo

Return: N - Current record number.

Example:

DbSelectArea("SA1")
DbGoTop()
Conout("Record number: " + Str(RecNo()))

LastRec

Returns the total number of records in the current work area.

Syntax: LastRec() --> nLastRec

Return: N - Total number of records.

Example:

DbSelectArea("SA1")
Conout("Total records: " + Str(LastRec()))

Eof

Returns whether the record pointer is past the last record.

Syntax: Eof() --> lEof

Return: L - .T. if at end-of-file.

Example:

DbSelectArea("SA1")
DbGoTop()
While !Eof()
    // Process record
    DbSkip()
EndDo

Bof

Returns whether the record pointer is before the first record.

Syntax: Bof() --> lBof

Return: L - .T. if at beginning-of-file.

Example:

DbSelectArea("SA1")
DbGoBottom()
While !Bof()
    // Process record in reverse
    DbSkip(-1)
EndDo

Deleted

Returns whether the current record is marked for deletion.

Syntax: Deleted() --> lDeleted

Return: L - .T. if the record is deleted.

Example:

DbSelectArea("SA1")
DbGoTop()
If !Deleted()
    Conout("Active record: " + SA1->A1_NOME)
EndIf

DbSetFilter

Sets a filter condition on the current work area.

Syntax: DbSetFilter( bFilter [, cFilter] ) --> NIL

ParamTypeDescription
bFilterBCode block with filter expression
cFilterCFilter expression as string (optional, for display)

Return: NIL

Example:

DbSelectArea("SA1")
DbSetFilter({|| SA1->A1_TIPO == "F"}, 'SA1->A1_TIPO == "F"')
DbGoTop()
While !Eof()
    Conout(SA1->A1_NOME) // Only physical person customers
    DbSkip()
EndDo
DbClearFilter()

IndexOrd

Returns the current index order number.

Syntax: IndexOrd() --> nOrder

Return: N - Current index order number.

Example:

DbSelectArea("SA1")
DbSetOrder(3)
Conout("Current index: " + Str(IndexOrd())) // 3

RetSqlName

Returns the physical SQL table name from the logical alias.

Syntax: RetSqlName( cAlias ) --> cTableName

ParamTypeDescription
cAliasCLogical alias (e.g., "SA1")

Return: C - Physical SQL table name (e.g., "SA1010").

Example:

Local cTable := RetSqlName("SA1") // "SA1010" (depends on company/branch)
Local cQuery := "SELECT * FROM " + cTable + " WHERE D_E_L_E_T_ = ' '"

DbCloseArea

Closes the current work area.

Syntax: DbCloseArea() --> NIL

Return: NIL

Example:

DbSelectArea("SA1")
// ... work with data ...
DbCloseArea()

DbUseArea

Opens a table in a specified work area.

Syntax: DbUseArea( lNewArea, cDriver, cFile, cAlias, lShared, lReadOnly ) --> NIL

ParamTypeDescription
lNewAreaL.T. to select a new work area
cDriverCDatabase driver (e.g., "TOPCONN")
cFileCTable file name
cAliasCAlias for the work area
lSharedL.T. for shared access
lReadOnlyL.T. for read-only access

Return: NIL

Example:

DbUseArea(.T., "TOPCONN", RetSqlName("SA1"), "SA1_QRY", .T., .T.)

Alias

Returns the alias of the current or specified work area.

Syntax: Alias( [nWorkArea] ) --> cAlias

ParamTypeDescription
nWorkAreaNWork area number (optional, default: current)

Return: C - Alias name, or empty string if work area is not in use.

Example:

DbSelectArea("SA1")
Conout(Alias()) // "SA1"

Select

Returns the work area number for a given alias.

Syntax: Select( [cAlias] ) --> nWorkArea

ParamTypeDescription
cAliasCAlias name (optional, default: current)

Return: N - Work area number, or 0 if not found.

Example:

Local nArea := Select("SA1")
If nArea > 0
    Conout("SA1 is open in work area: " + Str(nArea))
EndIf

Used

Returns whether the current work area has a table open.

Syntax: Used() --> lUsed

Return: L - .T. if a table is open in the current work area.

Example:

DbSelectArea("SA1")
If Used()
    Conout("SA1 is open")
EndIf

FCount

Returns the number of fields in the current work area.

Syntax: FCount() --> nFieldCount

Return: N - Number of fields.

Example:

DbSelectArea("SA1")
Conout("Number of fields: " + Str(FCount()))

FieldName

Returns the name of a field by its position number.

Syntax: FieldName( nPosition ) --> cFieldName

ParamTypeDescription
nPositionNField position (1-based)

Return: C - Field name.

Example:

Local nI := 0

DbSelectArea("SA1")
For nI := 1 To FCount()
    Conout(FieldName(nI))
Next nI

FieldGet

Returns the value of a field by its position number.

Syntax: FieldGet( nPosition ) --> xValue

ParamTypeDescription
nPositionNField position (1-based)

Return: U - Field value.

Example:

Local xVal := NIL

DbSelectArea("SA1")
DbGoTop()
xVal := FieldGet(1) // Value of first field

FieldPut

Sets the value of a field by its position number.

Syntax: FieldPut( nPosition, xValue ) --> xValue

ParamTypeDescription
nPositionNField position (1-based)
xValueUValue to set

Return: U - The value assigned.

Example:

DbSelectArea("SA1")
If RecLock("SA1", .F.)
    FieldPut(3, "New Value") // Sets the 3rd field
    MsUnlock()
EndIf

xFilial

Returns the branch code (filial) for a given alias, used in index key composition.

Syntax: xFilial( cAlias [, cFil] ) --> cRetFilial

Note: The second parameter cFil defaults to the system Private variable cFilAnt. Never use cFilial or cFilAnt as Local variable names — they are reserved by the framework.

ParamTypeDescription
cAliasCTable alias
nGroupNCompany group (optional)

Return: C - Branch code padded to the correct size.

Example:

DbSelectArea("SA1")
DbSetOrder(1)
// Seek using branch code
DbSeek(xFilial("SA1") + "000001" + "01")

Interface/UI Functions

MsgInfo

Displays an informational message dialog.

Syntax: MsgInfo( cMessage [, cTitle] ) --> NIL

ParamTypeDescription
cMessageCMessage text
cTitleCDialog title (default: "Information")

Return: NIL

Example:

MsgInfo("Operation completed successfully!", "Success")

MsgYesNo

Displays a Yes/No confirmation dialog (Yes is the default).

Syntax: MsgYesNo( cMessage [, cTitle] ) --> lYes

ParamTypeDescription
cMessageCQuestion text
cTitleCDialog title

Return: L - .T. if user clicked Yes, .F. if No.

Example:

If MsgYesNo("Do you want to continue?", "Confirmation")
    // User confirmed
    ProcessData()
EndIf

MsgAlert

Displays a warning/alert message dialog.

Syntax: MsgAlert( cMessage [, cTitle] ) --> NIL

ParamTypeDescription
cMessageCWarning message text
cTitleCDialog title (default: "Warning")

Return: NIL

Example:

MsgAlert("Some fields are missing!", "Validation")

MsgStop

Displays an error/stop message dialog.

Syntax: MsgStop( cMessage [, cTitle] ) --> NIL

ParamTypeDescription
cMessageCError message text
cTitleCDialog title (default: "Error")

Return: NIL

Example:

MsgStop("Critical error: unable to save record.", "Error")

MsgNoYes

Displays a No/Yes confirmation dialog (No is the default).

Syntax: MsgNoYes( cMessage [, cTitle] ) --> lYes

ParamTypeDescription
cMessageCQuestion text
cTitleCDialog title

Return: L - .T. if user clicked Yes, .F. if No.

Example:

If MsgNoYes("Are you sure you want to delete?", "Confirm Delete")
    DeleteRecord()
EndIf

FWExecView

Executes a standard CRUD view with an MVC model.

Syntax: FWExecView( cTitle, cSource, nOperation [, bOk [, bCancel [, nPercPosTela [, aEnableButtons]]]] ) --> nResult

ParamTypeDescription
cTitleCScreen title
cSourceCSource/alias name
nOperationNOperation type (MODEL_OPERATION_INSERT, _UPDATE, _DELETE, _VIEW)
bOkBCode block executed on OK
bCancelBCode block executed on Cancel
nPercPosTelaNScreen position percentage
aEnableButtonsAArray of enabled buttons

Return: N - Operation result.

Example:

FWExecView("Customer Registration", "SA1", MODEL_OPERATION_INSERT)

Enchoice

Creates an automatic editing panel for Protheus standard screens.

Syntax: Enchoice( cAlias, nReg, nOpc [, aCRA [, cLetra [, cTexto [, aAcho [, aPos [, aTela [, nModelo]]]]]]] ) --> NIL

ParamTypeDescription
cAliasCTable alias
nRegNRecord number
nOpcNOperation type (1=View, 2=View, 3=Insert, 4=Edit, 5=Delete)
aCRAAAdditional fields array

Return: NIL

Example:

Enchoice("SA1", 0, 3) // Opens insert form for SA1

MsDialog

Creates a standard Protheus dialog window.

Syntax: MsDialog():New( nTop, nLeft, nBottom, nRight, cTitle [, cStyle [, nClrText [, nClrBack [, oBrush [, oWnd [, lPixel [, oIcon]]]]]]] ) --> oDialog

ParamTypeDescription
nTopNTop position
nLeftNLeft position
nBottomNBottom position
nRightNRight position
cTitleCWindow title
lPixelLUse pixel coordinates (.T.)

Return: O - Dialog object.

Example:

Local oDlg
DEFINE MSDIALOG oDlg TITLE "My Dialog" FROM 0, 0 TO 300, 400 PIXEL
// Add controls here
ACTIVATE MSDIALOG oDlg CENTERED

MsGet

Creates an input field (GET) control.

Syntax: MsGet():New( nTop, nLeft, bSetGet, oWnd, nWidth, nHeight [, cPicture [, bValid [, nClrText [, nClrBack [, lPixel [, cF3]]]]]] ) --> oGet

ParamTypeDescription
nTopNTop position
nLeftNLeft position
bSetGetBCode block for get/set variable value
oWndOParent window
nWidthNControl width
nHeightNControl height
cPictureCInput picture mask
lPixelLUse pixel coordinates

Return: O - Get object.

Example:

Local cName := Space(30)
@ 10, 10 MSGET cName SIZE 100, 12 OF oDlg PIXEL

MsBrowse

Creates a data browse control for table navigation.

Syntax: MsBrowse():New( nTop, nLeft, nBottom, nRight, nStyle, bChange, oWnd [, aHeaders [, aColSizes [, aCols [, cAlias]]]] ) --> oBrowse

ParamTypeDescription
nTopNTop position
nLeftNLeft position
nBottomNBottom position
nRightNRight position
oWndOParent window
cAliasCTable alias to browse

Return: O - Browse object.

Example:

Local oBrw
DbSelectArea("SA1")
DbSetOrder(1)
oBrw := MsBrowse():New(5, 5, 200, 350,, , oDlg,,,,,"SA1")

MsNewGetDados

Creates a grid control for detail data entry (used in master-detail screens).

Syntax: MsNewGetDados():New( nTop, nLeft, nBottom, nRight, nStyle, cLinOk, cTudoOk, cIniCpos, aAlter, nFreeze, nMax, cFieldOk, cSuperDel, cDelOk, oWnd, aHeader, aCols ) --> oGetDados

ParamTypeDescription
nTopNTop position
nLeftNLeft position
nBottomNBottom position
nRightNRight position
cLinOkCLine validation function name
cTudoOkCTotal validation function name
aHeaderAColumn headers array
aColsAData columns array

Return: O - GetDados grid object.

Example:

Local oGetD
Local aHeader := {}
Local aCols   := {}
// Build header and cols from SX3 definitions
oGetD := MsNewGetDados():New(60, 0, 200, 400,, "AllwaysTrue()", ;
    "AllwaysTrue()",, , 0, 99,,,, oDlg, aHeader, aCols)

Alert

Displays a simple alert message with optional button choices.

Syntax: Alert( cMessage [, aButtons] ) --> nChoice

ParamTypeDescription
cMessageCMessage text
aButtonsAArray of button labels (optional)

Return: N - Number of the button pressed (1-based).

Example:

Local nOpt := Alert("Choose an option:", {"Save", "Cancel", "Help"})
If nOpt == 1
    // Save
EndIf

Pergunte

Loads and displays the parameter screen from SX1 dictionary.

Syntax: Pergunte( cGroup, lShowDialog [, cTitle] ) --> lConfirmed

ParamTypeDescription
cGroupCParameter group code (SX1 X1_GRUPO)
lShowDialogL.T. to display the dialog, .F. to load silently
cTitleCDialog title (optional)

Return: L - .T. if user confirmed, .F. if cancelled (always .T. when lShowDialog is .F.).

Example:

Local cFromDate := ""
Local cToDate   := ""

// Show parameter dialog for report filter
If Pergunte("MTR010", .T., "Sales Report Parameters")
    // Parameters are loaded into MV_PAR01, MV_PAR02, etc.
    cFromDate := MV_PAR01
    cToDate   := MV_PAR02
    RunReport(cFromDate, cToDate)
EndIf

// Load parameters silently (use last values)
Pergunte("MTR010", .F.)

File I/O Functions

FOpen

Opens a file for reading and/or writing.

Syntax: FOpen( cFileName [, nMode] ) --> nHandle

ParamTypeDescription
cFileNameCFull path to the file
nModeNOpen mode: 0=Read, 1=Write, 2=Read/Write (default: 0)

Return: N - File handle (>= 0 on success, -1 on failure).

Example:

Local nHandle := FOpen("C:\Temp\data.txt", 0) // Open for reading
If nHandle >= 0
    // Read file...
    FClose(nHandle)
Else
    Conout("Error opening file: " + Str(FError()))
EndIf

FRead

Reads data from an open file.

Syntax: FRead( nHandle, @cBuffer, nBytes ) --> nBytesRead

ParamTypeDescription
nHandleNFile handle from FOpen/FCreate
cBufferCVariable to receive data (passed by reference)
nBytesNNumber of bytes to read

Return: N - Number of bytes actually read.

Example:

Local nHandle := FOpen("C:\Temp\data.txt", 0)
Local cBuffer := Space(1024)
Local nRead := FRead(nHandle, @cBuffer, 1024)
cBuffer := Left(cBuffer, nRead)
Conout(cBuffer)
FClose(nHandle)

FWrite

Writes data to an open file.

Syntax: FWrite( nHandle, cData [, nBytes] ) --> nBytesWritten

ParamTypeDescription
nHandleNFile handle from FOpen/FCreate
cDataCData to write
nBytesNNumber of bytes to write (default: length of cData)

Return: N - Number of bytes actually written.

Example:

Local nHandle := FCreate("C:\Temp\output.txt")
FWrite(nHandle, "Line 1" + Chr(13) + Chr(10))
FWrite(nHandle, "Line 2" + Chr(13) + Chr(10))
FClose(nHandle)

FClose

Closes an open file.

Syntax: FClose( nHandle ) --> lSuccess

ParamTypeDescription
nHandleNFile handle to close

Return: L - .T. if closed successfully.

Example:

Local nHandle := FOpen("C:\Temp\data.txt")
// ... work with file ...
FClose(nHandle)

FErase

Deletes a file from the file system.

Syntax: FErase( cFileName ) --> nResult

ParamTypeDescription
cFileNameCFull path to the file to delete

Return: N - 0 on success, -1 on failure.

Example:

If FErase("C:\Temp\old_file.txt") == 0
    Conout("File deleted successfully")
EndIf

FRename

Renames a file.

Syntax: FRename( cOldName, cNewName ) --> nResult

ParamTypeDescription
cOldNameCCurrent file path
cNewNameCNew file path

Return: N - 0 on success, -1 on failure.

Example:

FRename("C:\Temp\old.txt", "C:\Temp\new.txt")

File

Checks if a file exists.

Syntax: File( cFileName ) --> lExists

ParamTypeDescription
cFileNameCFile path to check

Return: L - .T. if the file exists.

Example:

If File("C:\Temp\config.ini")
    Conout("Configuration file found")
EndIf

Directory

Returns an array with file and directory information.

Syntax: Directory( cPath [, cAttributes] ) --> aFiles

ParamTypeDescription
cPathCPath with optional wildcards
cAttributesCFile attributes filter ("D" for directories, "H" for hidden)

Return: A - Array of arrays: {cName, nSize, dDate, cTime, cAttributes}.

Example:

Local aFiles := Directory("C:\Temp\*.txt")
Local nI
For nI := 1 To Len(aFiles)
    Conout(aFiles[nI][1] + " - Size: " + Str(aFiles[nI][2]))
Next nI

MakeDir

Creates a new directory.

Syntax: MakeDir( cDirPath ) --> nResult

ParamTypeDescription
cDirPathCDirectory path to create

Return: N - 0 on success, -1 on failure.

Example:

If MakeDir("C:\Temp\Reports") == 0
    Conout("Directory created")
EndIf

CurDir

Returns the current directory.

Syntax: CurDir() --> cCurrentDir

Return: C - Current working directory path.

Example:

Local cDir := CurDir()
Conout("Current directory: " + cDir)

DirRemove

Removes an empty directory.

Syntax: DirRemove( cDirPath ) --> nResult

ParamTypeDescription
cDirPathCDirectory path to remove

Return: N - 0 on success, -1 on failure.

Example:

If DirRemove("C:\Temp\OldReports") == 0
    Conout("Directory removed")
EndIf

FSeek

Moves the file pointer to a specified position.

Syntax: FSeek( nHandle, nOffset [, nOrigin] ) --> nPosition

ParamTypeDescription
nHandleNFile handle
nOffsetNByte offset
nOriginNOrigin: 0=Beginning, 1=Current position, 2=End of file

Return: N - New file pointer position.

Example:

Local nHandle := FOpen("C:\Temp\data.bin", 0)
Local nSize := FSeek(nHandle, 0, 2) // Get file size by seeking to end
FSeek(nHandle, 0, 0)                // Return to beginning
Conout("File size: " + Str(nSize))
FClose(nHandle)

FCreate

Creates a new file or truncates an existing one.

Syntax: FCreate( cFileName [, nAttribute] ) --> nHandle

ParamTypeDescription
cFileNameCFile path to create
nAttributeNFile attribute: 0=Normal (default), 1=Read-only

Return: N - File handle (>= 0 on success, -1 on failure).

Example:

Local nHandle := FCreate("C:\Temp\log.txt")
If nHandle >= 0
    FWrite(nHandle, "Log started at: " + Time() + Chr(13) + Chr(10))
    FClose(nHandle)
EndIf

System Functions

GetMV

Retrieves the value of an MV_* system parameter from SX6.

Syntax: GetMV( cParamName ) --> xValue

ParamTypeDescription
cParamNameCParameter name (e.g., "MV_ESTADO")

Return: U - Parameter value (type depends on parameter definition).

Example:

Local cState := GetMV("MV_ESTADO")
Conout("Default state: " + cState)

PutMV

Sets the value of an MV_* system parameter in SX6.

Syntax: PutMV( cParamName, xValue ) --> NIL

ParamTypeDescription
cParamNameCParameter name
xValueUNew value

Return: NIL

Example:

PutMV("MV_ESTADO", "SP")

SuperGetMV

Retrieves the value of an MV_* parameter with default value support and caching.

Syntax: SuperGetMV( cParamName [, lHelp [, xDefault]] ) --> xValue

ParamTypeDescription
cParamNameCParameter name
lHelpLShow help if parameter not found (default: .T.)
xDefaultUDefault value if parameter does not exist

Return: U - Parameter value or default.

Example:

// Recommended over GetMV for better performance (uses cache)
Local nTaxRate := SuperGetMV("MV_TXICMS", .F., 18)
Local cCompany := SuperGetMV("MV_NOMEMP", .F., "My Company")

Conout

Outputs a message to the Protheus console log.

Syntax: Conout( cMessage [, cLogLevel] ) --> NIL

ParamTypeDescription
cMessageCMessage text to output
cLogLevelCLog level (optional)

Return: NIL

Example:

Conout("Processing started at: " + Time())
Conout("Record count: " + Str(LastRec()))

FWLogMsg

Writes a message to the Protheus application log with level and context.

Syntax: FWLogMsg( cLevel, cGroup, cCategory, cSource, cDetail, cLogId, cMessage ) --> NIL

ParamTypeDescription
cLevelCLog level: "INFO", "WARNING", "ERROR"
cGroupCGroup identifier
cCategoryCCategory identifier
cSourceCSource function/class
cDetailCDetailed description
cLogIdCUnique log ID
cMessageCLog message

Return: NIL

Example:

FWLogMsg("ERROR", "FATURAMENTO", "NF", "MATA461", ;
    "Error generating invoice", "001", ;
    "Invoice generation failed for order " + cOrder)

GetEnvServer

Returns the name of the current Protheus environment.

Syntax: GetEnvServer() --> cEnvironment

Return: C - Current environment name.

Example:

Local cEnv := GetEnvServer()
Conout("Running in environment: " + cEnv) // e.g., "P12"

GetArea

Saves the current work area state (alias, order, record position).

Syntax: GetArea() --> aArea

Return: A - Array with the saved work area state.

Example:

// Always save and restore area when working with multiple tables
Local aArea := GetArea()

DbSelectArea("SA1")
DbSetOrder(1)
DbGoTop()
// ... process SA1 ...

RestArea(aArea)

RestArea

Restores a previously saved work area state.

Syntax: RestArea( aArea ) --> NIL

ParamTypeDescription
aAreaAArea state array from GetArea()

Return: NIL

Example:

Local aArea := GetArea()
// ... do work in other areas ...
RestArea(aArea) // Restores original area, order, and position

Type

Returns the data type of an expression given as a string.

Syntax: Type( cExpression ) --> cType

ParamTypeDescription
cExpressionCExpression as a character string

Return: C - Type character: "C", "N", "D", "L", "A", "O", "B", "U" (undefined/error).

Example:

Local cType := Type("SA1->A1_NOME") // "C"
If Type("cMyVar") != "U"
    Conout("Variable exists")
EndIf

ValType

Returns the data type of a value.

Syntax: ValType( xValue ) --> cType

ParamTypeDescription
xValueUAny value

Return: C - Type character: "C", "N", "D", "L", "A", "O", "B", "U".

Example:

Local xVar := "Hello"
Conout(ValType(xVar)) // "C"

xVar := 42
Conout(ValType(xVar)) // "N"

cValToChar

Converts any value to its character string representation.

Syntax: cValToChar( xValue ) --> cString

ParamTypeDescription
xValueUAny value to convert

Return: C - String representation of the value.

Example:

Conout(cValToChar(42))        // "42"
Conout(cValToChar(.T.))       // ".T."
Conout(cValToChar(Date()))    // "04/03/2026"
Conout(cValToChar({"A","B"})) // "{...}"

Sleep

Pauses execution for a specified number of milliseconds.

Syntax: Sleep( nMilliseconds ) --> NIL

ParamTypeDescription
nMillisecondsNTime to sleep in milliseconds

Return: NIL

Example:

Conout("Waiting 3 seconds...")
Sleep(3000)
Conout("Done!")

Seconds

Returns the number of seconds elapsed since midnight.

Syntax: Seconds() --> nSeconds

Return: N - Seconds since midnight (with fractional precision).

Example:

Local nStart := Seconds()
Local nEnd   := 0

// ... perform operation ...
nEnd := Seconds()
Conout("Elapsed: " + Str(nEnd - nStart, 10, 3) + " seconds")

GetNextAlias

Returns the next available alias name for temporary work areas.

Syntax: GetNextAlias() --> cAlias

Return: C - Available alias name (e.g., "QRY001").

Example:

Local cAlias := GetNextAlias()
DbUseArea(.T., "TOPCONN", RetSqlName("SA1"), cAlias, .T., .T.)
// ... use temporary alias ...
(cAlias)->(DbCloseArea())

FWFreeArray

Frees memory used by an array (sets elements to NIL and resizes to 0).

Syntax: FWFreeArray( aArray ) --> NIL

ParamTypeDescription
aArrayAArray to free

Return: NIL

Example:

Local aLargeData := {}
// ... populate with thousands of records ...
// Free memory when done
FWFreeArray(aLargeData)

ExistBlock

Checks if a code block (point of entry / user exit) exists.

Syntax: ExistBlock( cBlockName ) --> lExists

ParamTypeDescription
cBlockNameCName of the function/code block

Return: L - .T. if the block exists in the RPO.

Example:

Local lOk := .T.

If ExistBlock("MT100LOK")
    lOk := ExecBlock("MT100LOK", .F., .F.)
EndIf

ExistFunc

Checks if a function exists in the compiled RPO.

Syntax: ExistFunc( cFuncName ) --> lExists

ParamTypeDescription
cFuncNameCFunction name

Return: L - .T. if the function exists.

Example:

If ExistFunc("MyCustomFunc")
    &("MyCustomFunc()")
EndIf

Company/Branch Management Functions (FW*)

CRITICAL: The Protheus framework maintains Private variables (cFilial, cFilAnt, cEmpAnt) for company/branch context. NEVER use these names as Local/Static variables — it shadows the system variables and causes data isolation bugs. Use cCodFil, cCodEmp instead. Always use the FW* functions below to read company/branch values.

FWCodFil

Returns the current branch code (M0_CODFIL).

Syntax: FWCodFil( [ cGrpCompany ] [, cEmpUDFil ] ) --> cCodFil

ParamTypeDescription
cGrpCompanyCCompany group to check (default: SM0->M0_CODIGO)
cEmpUDFilAArray with company, business unit, and branch (optional)

Return: C - Current branch code.

Example:

Local cCodFil := FWCodFil()
Conout("Branch code: " + cCodFil)

FWCodEmp

Returns the company code (or the company group if company is not configured in the group layout).

Syntax: FWCodEmp( [ cAlias ] ) --> cCodEmp

ParamTypeDescription
cAliasCTable alias to check (optional)

Return: C - Company code or company group.

Example:

Local cCodEmp := FWCodEmp()
Conout("Company: " + cCodEmp)

FWFilial

Returns the branch used by the system. When an alias is provided, returns the branch according to the table's sharing mode.

Syntax: FWFilial( [ cAlias ] ) --> cFil

ParamTypeDescription
cAliasCIf provided, returns branch according to sharing mode

Return: C - Branch code used by the system.

Example:

Local cFil := FWFilial("SA1")

FWCompany

Returns the company used by the system.

Syntax: FWCompany( [ cAlias ] ) --> cCompany

ParamTypeDescription
cAliasCAlias to evaluate (optional)

Return: C - Current company code.

Example:

Local cMyCompany := FWCompany()

FWGrpCompany

Returns the company group used by the system.

Syntax: FWGrpCompany() --> cGrpCompany

Return: C - Current company group.

Example:

Local cGrp := FWGrpCompany()

FWUnitBusiness

Returns the current business unit.

Syntax: FWUnitBusiness( [ cAlias ] ) --> cUnitBusiness

ParamTypeDescription
cAliasCAlias to evaluate (optional)

Return: C - Current business unit code.

Example:

Local cUnit := FWUnitBusiness()

FWAllCompany

Returns all companies for the given company group.

Syntax: FWAllCompany( [ cGrpCompany ] ) --> aAllCompany

ParamTypeDescription
cGrpCompanyCCompany group (default: SM0->M0_CODIGO)

Return: A - Array with all companies in the group.

Example:

Local aEmpresas := FWAllCompany()

FWAllFilial

Returns all branches for the given company group, company, and business unit.

Syntax: FWAllFilial( [ cCompany ] [, cUnitBusiness ] [, cGrpCompany ] [, lOnlyCode ] ) --> aAllFilial

ParamTypeDescription
cCompanyCCompany to check (optional)
cUnitBusinessABusiness unit to check (optional)
cGrpCompanyACompany group (default: SM0->M0_CODIGO)
lOnlyCodeLIf .T., returns only branch codes (default: .T.)

Return: A - Array with all branches.

Example:

Local aFiliais := FWAllFilial()

FWAllGrpCompany

Returns all available company groups.

Syntax: FWAllGrpCompany() --> aAllGroup

Return: A - Array with all company groups.

Example:

Local aGrupos := FWAllGrpCompany()

FWSizeFilial

Returns the size of the branch field.

Syntax: FWSizeFilial( [ cGrpCompany ] ) --> nFilSize

ParamTypeDescription
cGrpCompanyCCompany group (default: cEmpAnt)

Return: N - Branch field size.

Example:

Local nFilSize := FWSizeFilial()
Conout("Branch field size: " + cValToChar(nFilSize))

Transaction Functions

Begin Transaction

Starts a database transaction block. All operations within the block are atomic.

Syntax: BEGIN TRANSACTION

Example:

BEGIN TRANSACTION
    RecLock("SA1", .T.)
    SA1->A1_FILIAL := xFilial("SA1")
    SA1->A1_COD    := "000100"
    SA1->A1_LOJA   := "01"
    SA1->A1_NOME   := "Customer Name"
    MsUnlock()
END TRANSACTION

End Transaction

Ends a database transaction block, committing all changes.

Syntax: END TRANSACTION

Example:

BEGIN TRANSACTION
    // All database operations here are committed together
    RecLock("SC5", .F.)
    SC5->C5_NOTA := cInvoice
    MsUnlock()
END TRANSACTION

DisarmTransaction

Rolls back the current transaction, discarding all uncommitted changes.

Syntax: DisarmTransaction() --> NIL

Return: NIL

Example:

BEGIN TRANSACTION
    RecLock("SA1", .T.)
    SA1->A1_FILIAL := xFilial("SA1")
    SA1->A1_COD    := "000100"
    SA1->A1_NOME   := "Test"
    MsUnlock()

    If !ValidateData()
        DisarmTransaction() // Rolls back the insert
    EndIf
END TRANSACTION

TCSqlExec

Executes a SQL statement directly (INSERT, UPDATE, DELETE).

Syntax: TCSqlExec( cSql ) --> nResult

ParamTypeDescription
cSqlCSQL statement to execute

Return: N - 0 on success, negative on failure.

Example:

Local cSql := "UPDATE " + RetSqlName("SA1") + " SET A1_NOME = 'Updated' "
cSql += "WHERE A1_FILIAL = '" + xFilial("SA1") + "' "
cSql += "AND A1_COD = '000001' AND A1_LOJA = '01' "
cSql += "AND D_E_L_E_T_ = ' '"

If TCSqlExec(cSql) < 0
    Conout("SQL execution failed: " + TCSqlError())
EndIf

TCSetField

Sets the return field for a query opened with TCGenQry or embedded SQL.

Syntax: TCSetField( cAlias, cField, cType [, nSize [, nDecimals]] ) --> NIL

ParamTypeDescription
cAliasCQuery alias
cFieldCField name
cTypeCField type: "C", "N", "D", "L"
nSizeNField size
nDecimalsNNumber of decimal places

Return: NIL

Example:

Local cQuery := "SELECT A1_COD, A1_NOME, A1_SALDO FROM " + RetSqlName("SA1")
Local cAlias := GetNextAlias()

cQuery += " WHERE D_E_L_E_T_ = ' '"
DbUseArea(.T., "TOPCONN", TCGenQry(,,cQuery), cAlias, .F., .T.)
TCSetField(cAlias, "A1_SALDO", "N", 14, 2)

TCSPExec

Executes a stored procedure.

Syntax: TCSPExec( cProcName [, xParam1, xParam2, ...] ) --> nResult

ParamTypeDescription
cProcNameCStored procedure name
xParam1..NUParameters for the procedure

Return: N - Execution result.

Example:

Local nRet := TCSPExec("sp_update_balance", "000001", 1500.00)
If nRet < 0
    Conout("Stored procedure failed")
EndIf

Execution Functions

ExecBlock

Executes a user function or code block by name (used for Points of Entry).

Syntax: ExecBlock( cBlockName, lParam1, lParam2 [, aParams] ) --> xResult

ParamTypeDescription
cBlockNameCName of the function/block to execute
lParam1L.F. = do not pass parameters by reference
lParam2L.F. = standard execution
aParamsAArray of parameters to pass

Return: U - Return value from the executed block.

Example:

Local xRet    := NIL
Local aParams := {"SA1", 3}

// Execute a Point of Entry
If ExistBlock("MT010BRW")
    xRet := ExecBlock("MT010BRW", .F., .F.)
EndIf

// Execute with parameters
ExecBlock("MyValidation", .F., .F., aParams)

Eval

Evaluates a code block.

Syntax: Eval( bBlock [, xArg1, xArg2, ...] ) --> xResult

ParamTypeDescription
bBlockBCode block to evaluate
xArg1..NUArguments to pass to the code block

Return: U - Result of the code block evaluation.

Example:

Local bCalc := {|x, y| x * y + 10}
Local nResult := Eval(bCalc, 5, 3) // 25

Local bValid := {|cVal| !Empty(cVal)}
If Eval(bValid, cName)
    Conout("Name is valid")
EndIf

MsExecAuto

Executes a standard Protheus routine automatically (batch mode) for AxCadastro-based functions.

Syntax: MsExecAuto( {|x,y| FuncName(x,y)}, aFields, nOperation ) --> NIL

ParamTypeDescription
bFunctionBCode block referencing the standard function
aFieldsAArray of field name/value pairs: {{"field", value, NIL}}
nOperationNOperation: 3=Insert, 4=Update, 5=Delete

Return: NIL (check lMsErroAuto for errors, use GetAutoGRLog() for error messages).

Example:

Local aFields := {}
Local cError  := ""

Private lMsErroAuto := .F.

aAdd(aFields, {"A1_FILIAL", xFilial("SA1"), NIL})
aAdd(aFields, {"A1_COD",    "000100",        NIL})
aAdd(aFields, {"A1_LOJA",   "01",            NIL})
aAdd(aFields, {"A1_NOME",   "Auto Customer", NIL})
aAdd(aFields, {"A1_TIPO",   "F",             NIL})

MsExecAuto({|x,y| MATA030(x,y)}, aFields, 3) // Insert

If lMsErroAuto
    cError := GetAutoGRLog()
    Conout("Error in MsExecAuto: " + cError)
EndIf

FWMVCRotAuto

Executes MVC model operations automatically (batch mode).

Syntax: FWMVCRotAuto( oModel, cModelId, nOperation, aFieldValues [, lVerbose] ) --> lSuccess

ParamTypeDescription
oModelOMVC model object (or NIL to use cModelId)
cModelIdCModel identifier (function name)
nOperationNOperation: MODEL_OPERATION_INSERT (3), _UPDATE (4), _DELETE (5)
aFieldValuesAArray of {cFormId, {{"field", value}, ...}}
lVerboseLDisplay log messages

Return: L - .T. if operation succeeded.

Example:

Local aData   := {}
Local aHeader := {}
Local aItems  := {}
Local lRet    := .F.
Local oModel  := NIL
Local cError  := ""

// Header data (FormGrid)
aAdd(aHeader, {"A1_FILIAL", xFilial("SA1")})
aAdd(aHeader, {"A1_COD",    "000200"})
aAdd(aHeader, {"A1_LOJA",   "01"})
aAdd(aHeader, {"A1_NOME",   "MVC Customer"})

aAdd(aData, {"SA1MASTER", aHeader})

lRet := FWMVCRotAuto(NIL, "MATA030", MODEL_OPERATION_INSERT, aData)

If !lRet
    oModel := FWLoadModel("MATA030")
    cError := oModel:GetErrorMessage()
    Conout("MVC Error: " + cError)
EndIf

u_ (User Function Call)

Calls a user-defined function by name. In ADVPL, functions prefixed with User Function are called with u_ prefix.

Syntax: u_FuncName( [xParams] ) --> xResult

Example:

// Definition
User Function MyCalc(nVal1, nVal2)
    Local nResult := nVal1 + nVal2
Return nResult
// Call
Local nTotal := u_MyCalc(10, 20) // 30

Network/REST Functions

HttpGet

Performs an HTTP GET request.

Syntax: HttpGet( cUrl, cGetParms, nTimeOut, aHeaders, @cResponse ) --> lSuccess

ParamTypeDescription
cUrlCTarget URL
cGetParmsCQuery string parameters
nTimeOutNTimeout in seconds
aHeadersAArray of request headers
cResponseCVariable to receive response (by reference)

Return: L - .T. if request succeeded.

Example:

Local cUrl      := "https://api.example.com/data"
Local cResponse := ""
Local aHeaders  := {"Content-Type: application/json", "Authorization: Bearer token123"}

If HttpGet(cUrl, "", 30, aHeaders, @cResponse)
    Conout("Response: " + cResponse)
Else
    Conout("HTTP GET failed")
EndIf

HttpPost

Performs an HTTP POST request.

Syntax: HttpPost( cUrl, cPostParms, nTimeOut, aHeaders, @cResponse ) --> lSuccess

ParamTypeDescription
cUrlCTarget URL
cPostParmsCPOST body content
nTimeOutNTimeout in seconds
aHeadersAArray of request headers
cResponseCVariable to receive response (by reference)

Return: L - .T. if request succeeded.

Example:

Local cUrl      := "https://api.example.com/customers"
Local cBody     := '{"name": "John", "code": "000001"}'
Local cResponse := ""
Local aHeaders  := {"Content-Type: application/json"}

If HttpPost(cUrl, cBody, 30, aHeaders, @cResponse)
    Conout("Response: " + cResponse)
EndIf

FWRest

Framework class for building REST API services (server-side).

Syntax: FWRest():New( cRoute ) --> oRest

ParamTypeDescription
cRouteCAPI route path

Return: O - FWRest object.

Example:

#Include "tlpp-core.th"
#Include "tlpp-rest.th"

@Get("/api/v1/customers")
User Function getCustomers()
    Local oJson     := JsonObject():New()
    Local jResponse := JsonObject():New()
    Local jCust     := NIL

    DbSelectArea("SA1")
    DbSetOrder(1)
    DbGoTop()

    jResponse["customers"] := {}
    While !Eof()
        jCust := JsonObject():New()
        jCust["code"] := Alltrim(SA1->A1_COD)
        jCust["name"] := Alltrim(SA1->A1_NOME)
        aAdd(jResponse["customers"], jCust)
        DbSkip()
    EndDo

    oRest:setResponse(jResponse:toJson())
    oRest:setStatusCode(200)
Return

WsRestFul

Legacy class for creating RESTful web services.

Syntax: WsRestFul cServiceName DESCRIPTION cDescription FORMAT APPLICATION_JSON

Example:

WsRestFul CustomerService DESCRIPTION "Customer API" FORMAT APPLICATION_JSON

    WsData cCode As String

    WsMethod GET DESCRIPTION "Get customer" ;
        WSSYNTAX "/api/customer/{code}" ;
        PATH "/api/customer"

End WsRestFul

WsMethod GET WsReceive cCode WsService CustomerService
    Local oJson := JsonObject():New()

    DbSelectArea("SA1")
    DbSetOrder(1)
    If DbSeek(xFilial("SA1") + ::cCode)
        oJson["code"] := Alltrim(SA1->A1_COD)
        oJson["name"] := Alltrim(SA1->A1_NOME)
        ::SetResponse(oJson:toJson())
    Else
        ::SetResponse('{"error": "Not found"}')
        ::SetStatus(404)
    EndIf
Return .T.

FWJsonDeserialize

Deserializes a JSON string into an ADVPL object or hash map.

Syntax: FWJsonDeserialize( cJson, @xResult ) --> lSuccess

ParamTypeDescription
cJsonCJSON string
xResultUVariable to receive the deserialized object (by reference)

Return: L - .T. if deserialization succeeded.

Example:

Local cJson := '{"name": "John", "age": 30, "active": true}'
Local oResult

If FWJsonDeserialize(cJson, @oResult)
    Conout("Name: " + oResult:name)
    Conout("Age: " + Str(oResult:age))
EndIf

FWJsonSerialize

Serializes an ADVPL object to a JSON string.

Syntax: FWJsonSerialize( xValue [, lFormatted] ) --> cJson

ParamTypeDescription
xValueUValue to serialize (object, array, hash)
lFormattedL.T. for pretty-printed JSON (default: .F.)

Return: C - JSON string representation.

Example:

Local oData := JsonObject():New()
Local cJson := ""

oData["name"] := "John"
oData["age"]  := 30
oData["items"] := {"A", "B", "C"}

cJson := FWJsonSerialize(oData, .T.)
Conout(cJson)

JsonObject

Creates a new JSON object for building and parsing JSON data.

Syntax: JsonObject():New() --> oJson

Return: O - New JsonObject instance.

Example:

Local oJson  := JsonObject():New()
Local cJson  := ""
Local oJson2 := JsonObject():New()

// Build JSON
oJson["name"]    := "Protheus"
oJson["version"] := 12
oJson["modules"] := {"Faturamento", "Financeiro", "Estoque"}

// Convert to string
cJson := oJson:toJson()

// Parse from string
oJson2:fromJson('{"status": "ok", "count": 42}')
Conout(oJson2["status"]) // "ok"

FreeObj(oJson)
FreeObj(oJson2)

FWCallRest

Utility class for making REST API calls from ADVPL.

Syntax: FWCallRest():New() --> oCallRest

Return: O - FWCallRest instance.

Example:

Local oRest     := FWCallRest():New()
Local lRet      := .F.
Local cResponse := ""

oRest:SetPath("/api/v1/customers")
oRest:SetMethod("GET")
oRest:AddHeader("Content-Type", "application/json")
oRest:AddHeader("Authorization", "Bearer " + cToken)

lRet := oRest:Execute()
If lRet
    cResponse := oRest:GetResult()
    Conout("Response: " + cResponse)
Else
    Conout("Error: " + Str(oRest:GetStatusCode()))
EndIf

Conversion Functions

cValToChar

Converts any value to its character representation. (See System Functions > cValToChar for details.)


Str

Converts a numeric value to a character string. (See Numeric Functions > Str for details.)


Val

Converts a character string to a numeric value. (See Numeric Functions > Val for details.)


DtoC

Converts a date to a character string. (See Date/Time Functions > DtoC for details.)


CtoD

Converts a character string to a date. (See Date/Time Functions > CtoD for details.)


DtoS

Converts a date to YYYYMMDD string format. (See Date/Time Functions > DtoS for details.)


StoD

Converts a YYYYMMDD string to a date. (See Date/Time Functions > StoD for details.)


Transform

Formats a value according to a picture mask. (See String Functions > Transform for details.)


Iif

Inline conditional expression (ternary operator equivalent).

Syntax: Iif( lCondition, xTrue, xFalse ) --> xResult

ParamTypeDescription
lConditionLCondition to evaluate
xTrueUValue returned if condition is .T.
xFalseUValue returned if condition is .F.

Return: U - xTrue or xFalse depending on the condition.

Example:

Local cStatus := Iif(nSaldo > 0, "Active", "Inactive")
Local nDiscount := Iif(lVIP, nTotal * 0.15, nTotal * 0.05)

// Nested Iif
Local cLevel := Iif(nScore >= 90, "A", Iif(nScore >= 70, "B", "C"))

Additional Commonly Used Functions

Empty

Checks if a value is empty (blank string, zero, NIL, empty date, .F.).

Syntax: Empty( xValue ) --> lEmpty

ParamTypeDescription
xValueUValue to check

Return: L - .T. if the value is considered empty.

Example:

If Empty(cName)
    MsgAlert("Name is required!")
EndIf
// Empty("") == .T., Empty(0) == .T., Empty(.F.) == .T.
// Empty(NIL) == .T., Empty(CtoD("")) == .T.

TCSqlError

Returns the last SQL error message.

Syntax: TCSqlError() --> cErrorMessage

Return: C - SQL error message.

Example:

If TCSqlExec(cSql) < 0
    Conout("SQL Error: " + TCSqlError())
EndIf

TCGenQry

Generates a query for use with DbUseArea and the TOPCONN driver.

Syntax: TCGenQry( nParam1, nParam2, cQuery ) --> cQueryPath

ParamTypeDescription
nParam1NReserved (pass NIL)
nParam2NReserved (pass NIL)
cQueryCSQL SELECT query

Return: C - Internal query path for use with DbUseArea.

Example:

Local cQuery := "SELECT A1_COD, A1_NOME FROM " + RetSqlName("SA1")
Local cAlias := GetNextAlias()

cQuery += " WHERE A1_FILIAL = '" + xFilial("SA1") + "'"
cQuery += " AND D_E_L_E_T_ = ' '"
cQuery += " ORDER BY A1_COD"

DbUseArea(.T., "TOPCONN", TCGenQry(,,cQuery), cAlias, .F., .T.)

While !(cAlias)->(Eof())
    Conout((cAlias)->A1_COD + " - " + (cAlias)->A1_NOME)
    (cAlias)->(DbSkip())
EndDo

(cAlias)->(DbCloseArea())

FreeObj

Releases memory used by an object.

Syntax: FreeObj( oObject ) --> NIL

ParamTypeDescription
oObjectOObject to release

Return: NIL

Example:

Local oJson := JsonObject():New()
oJson["key"] := "value"
// ... use object ...
FreeObj(oJson)
oJson := NIL

Posicione

Positions on a record and returns a field value from any table.

Syntax: Posicione( cAlias, nOrder, cKey, cField ) --> xValue

ParamTypeDescription
cAliasCTable alias
nOrderNIndex order
cKeyCSeek key
cFieldCField name to return

Return: U - Value of the specified field.

Example:

// Get customer name without changing current work area
Local cName := Posicione("SA1", 1, xFilial("SA1") + "000001" + "01", "A1_NOME")
Conout("Customer: " + cName)

Existcpo

Checks if a value exists in a specific table field.

Syntax: ExistCpo( cAlias, cValue [, nOrder] ) --> lExists

ParamTypeDescription
cAliasCTable alias
cValueCValue to search for (branch is prepended automatically)
nOrderNIndex order (default: 1)

Return: L - .T. if the value exists.

Example:

// Check if customer code exists
If ExistCpo("SA1", "00000101")
    Conout("Customer exists")
EndIf

FWLoadModel

Loads an MVC model definition.

Syntax: FWLoadModel( cSource ) --> oModel

ParamTypeDescription
cSourceCModel source function name

Return: O - Model object.

Example:

Local oModel  := FWLoadModel("MATA030")
Local oMaster := NIL

oModel:SetOperation(MODEL_OPERATION_INSERT)
oModel:Activate()

oMaster := oModel:GetModel("SA1MASTER")
oMaster:SetValue("A1_COD",  "000300")
oMaster:SetValue("A1_LOJA", "01")
oMaster:SetValue("A1_NOME", "Model Customer")

If oModel:VldData()
    oModel:CommitData()
Else
    Conout("Validation error: " + oModel:GetErrorMessage())
EndIf

oModel:DeActivate()
FreeObj(oModel)

MsOpenQuery

Opens a SQL query as a work area (simplified alternative to TCGenQry + DbUseArea).

Syntax: MsOpenQuery( cQuery, cAlias ) --> NIL

ParamTypeDescription
cQueryCSQL SELECT query
cAliasCAlias name for the result set

Return: NIL

Example:

Local cQuery := "SELECT A1_COD, A1_NOME FROM " + RetSqlName("SA1")
Local cAlias := GetNextAlias()

cQuery += " WHERE D_E_L_E_T_ = ' '"

MsOpenQuery(cQuery, cAlias)

While !(cAlias)->(Eof())
    Conout((cAlias)->A1_COD + " - " + (cAlias)->A1_NOME)
    (cAlias)->(DbSkip())
EndDo

(cAlias)->(DbCloseArea())

GetAutoGRLog

Returns the error log from the last MsExecAuto execution.

Syntax: GetAutoGRLog() --> cErrorLog

Return: C - Formatted error log string.

Example:

Local cLog := ""

MsExecAuto({|x,y| MATA030(x,y)}, aFields, 3)

If lMsErroAuto
    cLog := GetAutoGRLog()
    Conout("MsExecAuto errors:")
    Conout(cLog)
EndIf

TReport Classes

TReport

Class for creating customizable reports, replacing SetPrint, SetDefault, RptStatus, and Cabec functions.

Syntax: TReport():New( cReport, cTitle, uParam, bAction, cDescription, lLandscape, uTotalText, lTotalInLine, cPageTText, lPageTInLine, lTPageBreak, nColSpace ) --> oReport

ParamTypeDescription
cReportCReport identifier name (e.g., "MATR010")
cTitleCReport title
uParamC/BParameter group from SX1 dictionary, or code block for custom parameters
bActionBCode block executed when user confirms printing
cDescriptionCReport description
lLandscapeL.T. for landscape orientation (default: .F. portrait)
uTotalTextC/BReport totalizer text (character or code block)
lTotalInLineL.T. to print totalizer cells in line
cPageTTextCPage totalizer text
lPageTInLineL.T. to print page totalizer in line
lTPageBreakL.T. for page break after printing totalizer
nColSpaceNSpacing between columns

Return: O - TReport object.

Key methods: SetPortrait(), SetLandscape(), SetTotalInLine(l), SetLineHeight(n), PrintDialog().

Example:

#Include "TOTVS.CH"
#Include "rptdef.ch"

Local oReport  := NIL
Local oSection := NIL

oReport := TReport():New("MATR010", "Customer Report", "MTR010", ;
    {|oReport| oSection:Print()}, "Customer listing report")

oSection := TRSection():New(oReport, "Customers", {"SA1"})

TRCell():New(oSection, "A1_COD",  "SA1", "Code")
TRCell():New(oSection, "A1_NOME", "SA1", "Name")

oReport:PrintDialog()

TRSection

Defines a section within a TReport, representing a data grouping tied to one or more tables.

Syntax: TRSection():New( oParent, cTitle, uTable, aOrder, lLoadCells, lLoadOrder, uTotalText, lTotalInLine, lHeaderPage, lHeaderBreak, lPageBreak, lLineBreak, nLeftMargin, lLineStyle, nColSpace, lAutoSize ) --> oSection

ParamTypeDescription
oParentOParent TReport object (or parent TRSection for sub-sections)
cTitleCSection title
uTableC/ATable alias or array of aliases (first is the main processing table)
aOrderAArray of index order descriptions (converted to TROrder objects)
lLoadCellsL.T. to automatically load cells from the data dictionary
lLoadOrderL.T. to automatically load orders from the data dictionary
uTotalTextC/BTotalizer text (character or code block)
lTotalInLineL.T. to print totalizer in line
lHeaderPageL.T. to print header on every page
lHeaderBreakL.T. to print header on break
lPageBreakL.T. for page break between groups
lLineBreakL.T. for line break
nLeftMarginNLeft margin
lLineStyleL.T. to enable line style
nColSpaceNColumn spacing
lAutoSizeL.T. to auto-size columns

Return: O - TRSection object.

Key methods: Init(), Print(), PrintLine(), Finish(), SetTotalInLine(l).

Example:

Local oSection := TRSection():New(oReport, "Customers", {"SA1"}, ;
    {"By Code", "By Name"})

TRCell():New(oSection, "A1_COD",  "SA1", "Code")
TRCell():New(oSection, "A1_NOME", "SA1", "Name")

TRCell

Defines a printing cell (column) within a TRSection.

Syntax: TRCell():New( oSection, cField, cAlias, cTitle, cPicture, nSize, lPixel, bBlock, cAlign, lLineBreak, cHeaderAlign, lCellBreak, nColSpace, lAutoSize, nClrBack, nClrFore, lBold ) --> oCell

ParamTypeDescription
oSectionOParent TRSection object
cFieldCField name
cAliasCTable alias
cTitleCColumn header title
cPictureCPicture format mask
nSizeNColumn width
lPixelL.T. to use pixel sizing
bBlockBCode block for custom printing
cAlignCCell alignment ("LEFT", "CENTER", "RIGHT")
lLineBreakL.T. to break line after cell
cHeaderAlignCHeader alignment
lCellBreakL.T. to break cell content
nColSpaceNColumn spacing
lAutoSizeL.T. for auto-sizing
nClrBackNBackground color
nClrForeNForeground color
lBoldL.T. for bold text

Return: O - TRCell object.

Example:

TRCell():New(oSection, "A1_COD",  "SA1", "Code",, 50)
TRCell():New(oSection, "A1_NOME", "SA1", "Name",, 200)
TRCell():New(oSection, "A1_TIPO", "SA1", "Type",, 30,,,, .T.) // Line break after

TRFunction

Creates a totalizer/aggregation function attached to a TRCell. Inherits from TRCell.

Syntax: TRFunction():New( oCell, cField, cFunction, oBreak, cFormula, cPicture ) --> oFunction

ParamTypeDescription
oCellOTarget TRCell object for the totalizer
cFieldCField name to aggregate (NIL to use the cell's field)
cFunctionCAggregation type: "SUM", "COUNT", "AVG", "MAX", "MIN"
oBreakOTRBreak object defining where to print the total (NIL for grand total)
cFormulaCCustom formula expression
cPictureCPicture format for the result

Return: O - TRFunction object.

Example:

// Sum the A1_SALDO field at the end of the report
TRFunction():New(oCell, NIL, "SUM",, , "@E 999,999,999.99")

// Count records with a break
TRFunction():New(oCell, NIL, "COUNT", oBreak)

TRBreak

Defines a break point in a TRSection for grouping and subtotaling.

Syntax: TRBreak():New( oSection, oCell, cLabel, lPageBreak ) --> oBreak

ParamTypeDescription
oSectionOParent TRSection object
oCellOTRCell that triggers the break (grouping field)
cLabelC/BBreak label/description (character or code block)
lPageBreakL.T. for page break on group change

Return: O - TRBreak object.

Example:

// Break by customer type
Local oCellType := TRCell():New(oSection, "A1_TIPO", "SA1", "Type")
Local oBreak    := TRBreak():New(oSection, oCellType, "Subtotal by Type", .F.)

// Sum with break
TRFunction():New(oCellSaldo, NIL, "SUM", oBreak)

FWFormBrowse / FWMBrowse Classes

FWMBrowse

Class providing a grid browse object with side buttons and column details based on the data dictionary. Used in MVC interfaces.

Syntax: FWMBrowse():New() --> oBrowse

Return: O - FWMBrowse object.

Key methods:

MethodSyntaxDescription
SetAliasSetAlias( cAlias )Sets the table alias for the browse
SetDescriptionSetDescription( cTitle )Sets the browse window title
AddLegendAddLegend( cCondition, cColor, cLabel )Adds a colored status legend
SetFilterDefaultSetFilterDefault( cFilter )Sets initial data filter
DisableDetailsDisableDetails()Removes detail view option
ActivateActivate()Displays and enables the browse

Example:

#Include "TOTVS.CH"

User Function MyBrowse()
    Local oBrowse := FWMBrowse():New()

    oBrowse:SetAlias("SA1")
    oBrowse:SetDescription("Customer Browse")
    oBrowse:AddLegend("SA1->A1_MSBLQL == '1'", "BR_VERMELHO", "Blocked")
    oBrowse:AddLegend("SA1->A1_MSBLQL != '1'", "BR_VERDE",    "Active")
    oBrowse:Activate()
Return

FWFormBrowse

Class providing a grid-type object with side buttons and column details. Similar to FWMBrowse but with additional form integration capabilities.

Syntax: FWFormBrowse():New() --> oFormBrowse

Return: O - FWFormBrowse object.

Key methods:

MethodSyntaxDescription
SetOwnerSetOwner( oDialog )Sets the parent dialog
AddButtonAddButton( cTitle, bAction, cParam, cOption, bVerify )Adds a side button
ActivateActivate( [oOwner] )Activates the browse

Example:

Local oFormBrowse := FWFormBrowse():New()
oFormBrowse:SetOwner(oDlg)
oFormBrowse:Activate()

FWFormStruct

Function that provides an object with data dictionary metadata structures, used by MVC Model and View classes.

Syntax: FWFormStruct( nType, cAlias, bFilter ) --> oStruct

ParamTypeDescription
nTypeNStructure type: 1 = Model (FWFormModelStruct), 2 = View (FWFormViewStruct)
cAliasCTable alias from the data dictionary (SX2)
bFilterBCode block for filtering fields from SX3 (optional)

Return: O - Structure object (FWFormModelStruct or FWFormViewStruct).

Example:

// Model structure with all fields
Local oModelStruct := FWFormStruct(1, "SA1")

// View structure with all fields
Local oViewStruct := FWFormStruct(2, "SA1")

// Model structure filtering specific fields
Local oFiltered := FWFormStruct(1, "SA1", ;
    {|cCampo| Alltrim(cCampo) $ "A1_COD,A1_LOJA,A1_NOME,A1_TIPO"})

Jobs / Multi-Threading Functions

StartJob

Executes an ADVPL function on a new thread (without interface).

Syntax: StartJob( cFuncName, cEnvironment, lWait [, xParam1, xParam2, ..., xParam25] ) --> lSuccess

ParamTypeDescription
cFuncNameCName of the function to execute (e.g., "u_MyJob")
cEnvironmentCEnvironment name (typically from GetEnvServer())
lWaitL.T. to wait for the job to finish, .F. to run asynchronously
xParam1..25UOptional parameters passed to the function (up to 25)

Return: L - .T. if the job was started successfully, .F. otherwise.

Example:

// Asynchronous job
StartJob("u_ProcessBatch", GetEnvServer(), .F., "SA1", Date())

// Synchronous job (waits for completion)
Local lOk := StartJob("u_GenerateReport", GetEnvServer(), .T., cReportId)
If !lOk
    Conout("Job failed to start")
EndIf

RpcSetEnv

Opens and initializes the Protheus environment in background threads or automated routines. Required when using StartJob.

Syntax: RpcSetEnv( cCodEmp, cCodFil, cUser, cPassword, cModule, cFunName, aTables, lShowFinal, lAbend, lOpenSX, lConnect ) --> lSuccess

IMPORTANT: When calling RpcSetEnv, never use cFilial, cFilAnt or cEmpAnt as variable names for the parameters — these are reserved Private variables. Use cCodEmp and cCodFil instead.

ParamTypeDescription
cCodEmpCCompany code (e.g., "99")
cCodFilCBranch code (e.g., "01")
cUserCUser login (optional)
cPasswordCUser password (optional)
cModuleCConnection module (default: "FAT")
cFunNameCFunction name for logging (default: "RPC")
aTablesAArray of table aliases to open immediately (optional)
lShowFinalL.T. to control lMsFinalAuto variable
lAbendL.T. to show error on license validation failure
lOpenSXL.T. to open dictionary tables from SM0
lConnectL.T. to connect to database server

Return: L - .T. if the environment was successfully prepared.

Example:

User Function MyJob(cParam)
    Local lEnv := .F.

    lEnv := RpcSetEnv("99", "01")
    If !lEnv
        Conout("Failed to open environment")
        Return
    EndIf

    // Process data here...
    DbSelectArea("SA1")
    DbSetOrder(1)
    DbGoTop()
    While !Eof()
        // ...
        DbSkip()
    EndDo

    RpcClearEnv()
Return

RpcClearEnv

Releases the environment opened by RpcSetEnv, freeing the license and closing connections.

Syntax: RpcClearEnv() --> NIL

Return: NIL

Example:

RpcSetEnv("99", "01")
// ... perform operations ...
RpcClearEnv() // Always call after RpcSetEnv when done

Note: It is not necessary to call RpcClearEnv() after a StartJob(), since the thread is fully finalized upon its return.


LockByName

Creates a named semaphore (lock) on the license server to prevent concurrent execution of routines.

Syntax: LockByName( cName, lEmpresa, lFilial ) --> lCreated

ParamTypeDescription
cNameCSemaphore name identifier
lEmpresaL.T. to scope the lock by company
lFilialL.T. to scope the lock by branch

Return: L - .T. if the semaphore was created successfully, .F. if it already exists.

Example:

If !LockByName("MY_BATCH_PROCESS", .T., .F.)
    MsgAlert("Another user is already running this process!")
    Return
EndIf

// Execute exclusive routine
ProcessBatch()

UnlockByName("MY_BATCH_PROCESS", .T., .F.)

UnlockByName

Releases a named semaphore previously created by LockByName.

Syntax: UnlockByName( cName, lEmpresa, lFilial ) --> NIL

ParamTypeDescription
cNameCSemaphore name identifier (must match LockByName)
lEmpresaL.T. if the lock was scoped by company
lFilialL.T. if the lock was scoped by branch

Return: NIL

Example:

// Always release the lock after processing
LockByName("IMPORT_ROUTINE", .T., .T.)
// ... process ...
UnlockByName("IMPORT_ROUTINE", .T., .T.)

Email Classes

TMailManager

Class for managing email server communication (SMTP/POP3). Handles connection, authentication, and email transmission.

Syntax: TMailManager():New() --> oServer

Return: O - TMailManager object.

Key methods:

MethodSyntaxDescription
InitInit( cPopAddr, cSmtpAddr, cUser, cPass, nPopPort, nSmtpPort )Initializes server connection parameters
SetUseSSLSetUseSSL( lSSL )Enables/disables SSL encryption
SetUseTLSSetUseTLS( lTLS )Enables/disables TLS encryption
SetSMTPTimeoutSetSMTPTimeout( nTimeout )Sets SMTP connection timeout in seconds
SmtpConnectSmtpConnect() --> nErrorConnects to the SMTP server (0 = success)
SmtpAuthSmtpAuth( cUser, cPass ) --> nErrorAuthenticates with SMTP server
SendMailSendMail( oMessage ) --> nErrorSends an email message
SmtpDisconnectSmtpDisconnect() --> nErrorDisconnects from SMTP server
GetErrorStringGetErrorString( nError ) --> cErrorReturns error description

Example:

Local oServer  := TMailManager():New()
Local oMessage := TMailMessage():New()
Local nErr     := 0

// Configure server
oServer:SetUseSSL(.T.)
oServer:Init("", "smtp.gmail.com", "user@gmail.com", "password", 0, 465)

// Connect
nErr := oServer:SmtpConnect()
If nErr != 0
    Conout("SMTP Error: " + oServer:GetErrorString(nErr))
    Return
EndIf

// Authenticate
nErr := oServer:SmtpAuth("user@gmail.com", "password")

// Build message
oMessage:Clear()
oMessage:cFrom    := "user@gmail.com"
oMessage:cTo      := "recipient@company.com"
oMessage:cSubject := "Report Ready"
oMessage:cBody    := "The monthly report is attached."

// Send
nErr := oServer:SendMail(oMessage)
If nErr != 0
    Conout("Send Error: " + oServer:GetErrorString(nErr))
EndIf

oServer:SmtpDisconnect()

TMailMessage

Class representing an email message. Used together with TMailManager for composing and sending emails.

Syntax: TMailMessage():New() --> oMessage

Return: O - TMailMessage object.

Key properties:

PropertyTypeDescription
cFromCSender email address
cToCRecipient email address(es)
cCcCCarbon copy recipient(s)
cBccCBlind carbon copy recipient(s)
cSubjectCEmail subject
cBodyCEmail body content (plain text or HTML)

Key methods:

MethodSyntaxDescription
ClearClear()Resets the message object
AttachFileAttachFile( cFilePath )Attaches a file to the message
SendSend( oServer )Sends the message using a TMailManager instance

Example:

Local oMessage := TMailMessage():New()

oMessage:Clear()
oMessage:cFrom    := "system@company.com"
oMessage:cTo      := "manager@company.com"
oMessage:cCc      := "team@company.com"
oMessage:cSubject := "Invoice #" + cInvoice
oMessage:cBody    := "<html><body><h1>Invoice Generated</h1></body></html>"
oMessage:AttachFile("\reports\invoice_" + cInvoice + ".pdf")

TWsdlManager Class Methods

Class for consuming external SOAP Web Services from ADVPL. Loads WSDL, calls operations, and reads responses.

New (TWsdlManager)

Constructor - creates a new TWsdlManager instance.

Syntax: TWsdlManager():New() --> oWsdl

Return: O - TWsdlManager object.

ParseURL

Loads and parses a WSDL from a URL.

Syntax: oWsdl:ParseURL( cUrl ) --> lSuccess

ParamTypeDescription
cUrlCURL of the WSDL

Return: L - .T. if WSDL was loaded successfully.

ParseFile

Loads and parses a WSDL from a local file.

Syntax: oWsdl:ParseFile( cPath ) --> lSuccess

ParamTypeDescription
cPathCLocal file path of the WSDL

Return: L - .T. if WSDL was loaded successfully.

SetOperation

Selects the SOAP operation to call.

Syntax: oWsdl:SetOperation( cOperation ) --> lSuccess

ParamTypeDescription
cOperationCOperation name from the WSDL

Return: L - .T. if operation was found and selected.

SendSoapMsg

Sends a SOAP envelope message.

Syntax: oWsdl:SendSoapMsg( cXml ) --> lSuccess

ParamTypeDescription
cXmlCComplete SOAP XML envelope

Return: L - .T. if message was sent successfully.

GetParsedResponse

Returns the parsed response body after a successful SendSoapMsg.

Syntax: oWsdl:GetParsedResponse() --> cResponse

Return: C - Parsed response content.

GetSoapResponse

Returns the raw SOAP XML response.

Syntax: oWsdl:GetSoapResponse() --> cRawXml

Return: C - Raw SOAP XML response.

GetSoapMsg

Returns the SOAP message that will be or was sent.

Syntax: oWsdl:GetSoapMsg() --> cSoapXml

Return: C - SOAP XML message.

ListOperations

Lists available operations for the current service port.

Syntax: oWsdl:ListOperations() --> aOperations

Return: A - Array of operation names.

SetPort

Selects a service port from the WSDL.

Syntax: oWsdl:SetPort( cPort ) --> lSuccess

ParamTypeDescription
cPortCPort/service name

Return: L - .T. if port was selected.

SetValue

Sets an input parameter value for the operation.

Syntax: oWsdl:SetValue( cParam, cValue ) --> lSuccess

ParamTypeDescription
cParamCParameter name
cValueCParameter value

Return: L - .T. if value was set.

Key Properties (TWsdlManager)

PropertyTypeDescription
cErrorCLast error message
cFaultCodeCSOAP Fault code (check after SendSoapMsg)
cFaultSubCodeCSOAP Fault sub-code
cFaultStringCSOAP Fault description message
cFaultActorCSOAP Fault actor
nTimeoutNTimeout in seconds (default 120)
bNoCheckPeerCertL.T. to skip SSL certificate validation
lProcRespL.T. to auto-process response (default .T.)

IMPORTANT: SOAP Fault data is accessed via properties (cFaultCode, cFaultString, etc.), NOT via a method. There is NO GetSoapFault() method. There is NO ListServices() method — use SetPort() to select a port and ListOperations() to list operations.

Example:

Local oWsdl := TWsdlManager():New()
oWsdl:nTimeout := 120
oWsdl:bNoCheckPeerCert := .T.

If oWsdl:ParseURL(cUrl)
    oWsdl:SetOperation("OPERACAO")
    If oWsdl:SendSoapMsg(cEnvelope)
        If !Empty(oWsdl:cFaultCode)
            Conout("SOAP Fault: " + oWsdl:cFaultCode + " - " + oWsdl:cFaultString)
        Else
            cResp := oWsdl:GetParsedResponse()
        EndIf
    EndIf
EndIf

Legacy / Compatibility Functions

StaticCall (BLOCKED — DO NOT USE)

Executes a Static Function from another source file. COMPILATION BLOCKED since release 12.1.33. This function is TOTVS internal property and cannot be used in custom code.

Syntax: StaticCall( ProgramName, FunctionName [, xParam1, ..., xParamN] ) --> xResult

ParamTypeDescription
ProgramName-Program name containing the Static Function (literal, no quotes)
FunctionName-Static Function name to execute (literal, no quotes)
xParam1..NUParameters to pass to the function

Return: U - Return value from the executed Static Function.

CRITICAL: StaticCall() has its compilation BLOCKED since release 12.1.33. It is listed as TOTVS internal property. Refactor to use public User Functions or namespaced TLPP calls instead.

Example (legacy — for reference only, DO NOT use in new code):

// Call a Static Function from another program
Local aMenu := StaticCall(MATA030, MenuDef)

// Call with parameters
Local xRet := StaticCall(MyProgram, MyStaticFunc, "param1", 42)

Nesta pagina

Protheus Native Functions ReferenceString FunctionsAlltrimSubStrStrTranPadRPadLPadCUpperLowerLenAtRatStuffLeftRightReplicateSpaceTransformStrZeroCharRemAscChrDate/Time FunctionsDatedDataBaseDtoSStoDCtoDDtoCDayMonthYearDOWTimeElapTimeDaySubMonthSubDateValidNumeric FunctionsIntRoundAbsValStrNoRoundModLogSqrtMaxMinArray FunctionsaAddaDelaSizeaScanaSortaCloneArrayaFillaCopyaEvalaTailaInsDatabase FunctionsDbSelectAreaDbSetOrderDbSeekDbSkipDbGoTopDbGoBottomRecLockMsUnlockRecNoLastRecEofBofDeletedDbSetFilterIndexOrdRetSqlNameDbCloseAreaDbUseAreaAliasSelectUsedFCountFieldNameFieldGetFieldPutxFilialInterface/UI FunctionsMsgInfoMsgYesNoMsgAlertMsgStopMsgNoYesFWExecViewEnchoiceMsDialogMsGetMsBrowseMsNewGetDadosAlertPergunteFile I/O FunctionsFOpenFReadFWriteFCloseFEraseFRenameFileDirectoryMakeDirCurDirDirRemoveFSeekFCreateSystem FunctionsGetMVPutMVSuperGetMVConoutFWLogMsgGetEnvServerGetAreaRestAreaTypeValTypecValToCharSleepSecondsGetNextAliasFWFreeArrayExistBlockExistFuncCompany/Branch Management Functions (FW*)FWCodFilFWCodEmpFWFilialFWCompanyFWGrpCompanyFWUnitBusinessFWAllCompanyFWAllFilialFWAllGrpCompanyFWSizeFilialTransaction FunctionsBegin TransactionEnd TransactionDisarmTransactionTCSqlExecTCSetFieldTCSPExecExecution FunctionsExecBlockEvalMsExecAutoFWMVCRotAutou_ (User Function Call)Network/REST FunctionsHttpGetHttpPostFWRestWsRestFulFWJsonDeserializeFWJsonSerializeJsonObjectFWCallRestConversion FunctionscValToCharStrValDtoCCtoDDtoSStoDTransformIifAdditional Commonly Used FunctionsEmptyTCSqlErrorTCGenQryFreeObjPosicioneExistcpoFWLoadModelMsOpenQueryGetAutoGRLogTReport ClassesTReportTRSectionTRCellTRFunctionTRBreakFWFormBrowse / FWMBrowse ClassesFWMBrowseFWFormBrowseFWFormStructJobs / Multi-Threading FunctionsStartJobRpcSetEnvRpcClearEnvLockByNameUnlockByNameEmail ClassesTMailManagerTMailMessageTWsdlManager Class MethodsNew (TWsdlManager)ParseURLParseFileSetOperationSendSoapMsgGetParsedResponseGetSoapResponseGetSoapMsgListOperationsSetPortSetValueKey Properties (TWsdlManager)Legacy / Compatibility FunctionsStaticCall (BLOCKED — DO NOT USE)