TBlock - Code Block From Expression String

Fonte: source/classes/block.prg

TBlock creates Harbour code blocks (bBlock) from character expression strings at runtime. This enables dynamic evaluation of expressions entered by the user or read from configuration files. The class compiles the expression string using Harbour's & (macro) operator and stores the resulting code block. The Eval() method evaluates the block with optional parameters, while Exec() runs it for side effects.

DATA Members

DATATypeDescription
cExpressionCharacterThe expression string from which the code block was compiled
bBlockCodeblockThe compiled code block ready for evaluation

Methods

MethodDescription
New( cExpr )Create a TBlock object from expression string cExpr. Compiles it into bBlock
Eval( uPar1 .. uPar5 )Evaluate the code block with up to five parameters and return the result
Exec( uPar1 .. uPar5 )Evaluate the code block for side effects (return value is discarded)

Example: Runtime Expression Evaluation

#include "FiveWin.ch"

function Main()

   local cExpr, oBlock, nResult

   // Get expression from user input
   cExpr := "2 + 3 * 4"

   oBlock := TBlock():New( cExpr )
   if oBlock:bBlock != nil
      nResult := oBlock:Eval()
      ? cExpr + " = " + Str( nResult )    // 14
   endif

   // Expression with parameters
   oBlock := TBlock():New( "x + y" )
   if oBlock:bBlock != nil
      nResult := oBlock:Eval( 10, 20 )
      ? "x + y = " + Str( nResult )       // 30
   endif

   // Expression from config file
   local cConfigExpr := "Year( Date() ) - 2000"
   oBlock := TBlock():New( cConfigExpr )
   ? "Year offset:", oBlock:Eval()

   // Exec with side effects
   oBlock := TBlock():New( "MsgInfo( 'Hello from TBlock!' )" )
   oBlock:Exec()

return nil

Veja Também