uCalc SDK Interactive Examples

BracketSensitive

ID: 121

				
					using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
var Pattern = t.Pattern("< {etc} >");
t.Str("< a b c > d < (e f g) > h < (i) (j k) > l < m n o ( > p) q >");

// Note the difference in the final match

Pattern.BracketSensitive = true; // true is the default
Console.WriteLine($"BracketSensitive: {Pattern.BracketSensitive}");
Console.WriteLine("----------------------");
t.Find();
Console.WriteLine(t.Matches.Text);
Console.WriteLine("");

Pattern.BracketSensitive = false;
Console.WriteLine($"BracketSensitive: {Pattern.BracketSensitive}");
Console.WriteLine("-----------------------");

t.Find();
Console.WriteLine(t.Matches.Text);
Console.WriteLine("");

t.Str("( a b ( c ) d e )");
// Here parentheses are captured as regular tokens, not bracket pairs
var Pattern2a = t.Pattern("( {etc} (");
var Pattern2b = t.Pattern(") {etc} )");

Console.WriteLine("Brackets used as part of pattern");
Console.WriteLine("--------------------------------");
Pattern2a.BracketSensitive = true;
Pattern2b.BracketSensitive = true;
t.Find();
Console.WriteLine(t.Matches.Text);
Console.WriteLine("");
Pattern2a.BracketSensitive = false;
Pattern2b.BracketSensitive = false;
t.Find();
Console.WriteLine(t.Matches.Text);


				
			
BracketSensitive: True
----------------------
< a b c >
< (e f g) >
< (i) (j k) >
< m n o ( > p) q >

BracketSensitive: False
-----------------------
< a b c >
< (e f g) >
< (i) (j k) >
< m n o ( >

Brackets used as part of pattern
--------------------------------
( a b (
) d e )

( a b (
) d e )
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

#define tf(IsTrue) ((IsTrue) ? "True" : "False")

int main() {
   uCalc uc;
   auto t = uc.NewTransformer();
   auto Pattern = t.Pattern("< {etc} >");
   t.Str("< a b c > d < (e f g) > h < (i) (j k) > l < m n o ( > p) q >");

   // Note the difference in the final match

   Pattern.BracketSensitive(true); // true is the default
   cout << "BracketSensitive: " << tf(Pattern.BracketSensitive()) << endl;
   cout << "----------------------" << endl;
   t.Find();
   cout << t.Matches().Text() << endl;
   cout << "" << endl;

   Pattern.BracketSensitive(false);
   cout << "BracketSensitive: " << tf(Pattern.BracketSensitive()) << endl;
   cout << "-----------------------" << endl;

   t.Find();
   cout << t.Matches().Text() << endl;
   cout << "" << endl;

   t.Str("( a b ( c ) d e )");
   // Here parentheses are captured as regular tokens, not bracket pairs
   auto Pattern2a = t.Pattern("( {etc} (");
   auto Pattern2b = t.Pattern(") {etc} )");

   cout << "Brackets used as part of pattern" << endl;
   cout << "--------------------------------" << endl;
   Pattern2a.BracketSensitive(true);
   Pattern2b.BracketSensitive(true);
   t.Find();
   cout << t.Matches().Text() << endl;
   cout << "" << endl;
   Pattern2a.BracketSensitive(false);
   Pattern2b.BracketSensitive(false);
   t.Find();
   cout << t.Matches().Text() << endl;


}
				
			
BracketSensitive: True
----------------------
< a b c >
< (e f g) >
< (i) (j k) >
< m n o ( > p) q >

BracketSensitive: False
-----------------------
< a b c >
< (e f g) >
< (i) (j k) >
< m n o ( >

Brackets used as part of pattern
--------------------------------
( a b (
) d e )

( a b (
) d e )
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim t = uc.NewTransformer()
      Dim Pattern = t.Pattern("< {etc} >")
      t.Str("< a b c > d < (e f g) > h < (i) (j k) > l < m n o ( > p) q >")
      
      '// Note the difference in the final match
      
      Pattern.BracketSensitive = true '// true is the default
      Console.WriteLine($"BracketSensitive: {Pattern.BracketSensitive}")
      Console.WriteLine("----------------------")
      t.Find()
      Console.WriteLine(t.Matches.Text)
      Console.WriteLine("")
      
      Pattern.BracketSensitive = false
      Console.WriteLine($"BracketSensitive: {Pattern.BracketSensitive}")
      Console.WriteLine("-----------------------")
      
      t.Find()
      Console.WriteLine(t.Matches.Text)
      Console.WriteLine("")
      
      t.Str("( a b ( c ) d e )")
      '// Here parentheses are captured as regular tokens, not bracket pairs
      Dim Pattern2a = t.Pattern("( {etc} (")
      Dim Pattern2b = t.Pattern(") {etc} )")
      
      Console.WriteLine("Brackets used as part of pattern")
      Console.WriteLine("--------------------------------")
      Pattern2a.BracketSensitive = true
      Pattern2b.BracketSensitive = true
      t.Find()
      Console.WriteLine(t.Matches.Text)
      Console.WriteLine("")
      Pattern2a.BracketSensitive = false
      Pattern2b.BracketSensitive = false
      t.Find()
      Console.WriteLine(t.Matches.Text)
      
      
   End Sub
End Module
				
			
BracketSensitive: True
----------------------
< a b c >
< (e f g) >
< (i) (j k) >
< m n o ( > p) q >

BracketSensitive: False
-----------------------
< a b c >
< (e f g) >
< (i) (j k) >
< m n o ( >

Brackets used as part of pattern
--------------------------------
( a b (
) d e )

( a b (
) d e )
Calculates a monthly loan payment by defining a custom function with the standard amortization formula, showcasing a practical, real-world use case.

ID: 1267

				
					using uCalcSoftware;

var uc = new uCalc();
// Define a function for the standard loan payment formula
uc.DefineFunction("LoanPmt(rate, nper, pv) = Int((rate * pv) / (1 - (1 + rate)^-nper)*100)/100");

// Define variables for the calculation
uc.DefineVariable("monthly_rate = 0.05 / 12"); // 5% annual rate
uc.DefineVariable("periods = 30 * 12");      // 30 years
uc.DefineVariable("loan_amount = 200000");   // $200,000

Console.WriteLine(uc.EvalStr("LoanPmt(monthly_rate, periods, loan_amount)"));
				
			
1073.64
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   // Define a function for the standard loan payment formula
   uc.DefineFunction("LoanPmt(rate, nper, pv) = Int((rate * pv) / (1 - (1 + rate)^-nper)*100)/100");

   // Define variables for the calculation
   uc.DefineVariable("monthly_rate = 0.05 / 12"); // 5% annual rate
   uc.DefineVariable("periods = 30 * 12");      // 30 years
   uc.DefineVariable("loan_amount = 200000");   // $200,000

   cout << uc.EvalStr("LoanPmt(monthly_rate, periods, loan_amount)") << endl;
}
				
			
1073.64
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      '// Define a function for the standard loan payment formula
      uc.DefineFunction("LoanPmt(rate, nper, pv) = Int((rate * pv) / (1 - (1 + rate)^-nper)*100)/100")
      
      '// Define variables for the calculation
      uc.DefineVariable("monthly_rate = 0.05 / 12") '// 5% annual rate
      uc.DefineVariable("periods = 30 * 12")      '// 30 years
      uc.DefineVariable("loan_amount = 200000")   '// $200,000
      
      Console.WriteLine(uc.EvalStr("LoanPmt(monthly_rate, periods, loan_amount)"))
   End Sub
End Module
				
			
1073.64
Calculates a total price using predefined variables and demonstrates the effect of output formatting.

ID: 338

See: EvalStr
				
					using uCalcSoftware;

var uc = new uCalc();
// Define some context for the expression
uc.DefineVariable("price = 49.99");
uc.DefineVariable("quantity = 3");
uc.DefineConstant("TAX_RATE = 0.0825");

// Define a format for currency output
uc.Format("DataType: Double, Def: result = '$' + result");

// Expression to calculate total price, using variables
var expression = "price * quantity * (1 + TAX_RATE)";

// Evaluate with formatting enabled
Console.WriteLine($"Formatted Total: {uc.EvalStr(expression, true)}");

// Evaluate with formatting disabled
Console.WriteLine($"Raw Total: {uc.EvalStr(expression, false)}");
				
			
Formatted Total: $162.342525
Raw Total: 162.342525
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   // Define some context for the expression
   uc.DefineVariable("price = 49.99");
   uc.DefineVariable("quantity = 3");
   uc.DefineConstant("TAX_RATE = 0.0825");

   // Define a format for currency output
   uc.Format("DataType: Double, Def: result = '$' + result");

   // Expression to calculate total price, using variables
   auto expression = "price * quantity * (1 + TAX_RATE)";

   // Evaluate with formatting enabled
   cout << "Formatted Total: " << uc.EvalStr(expression, true) << endl;

   // Evaluate with formatting disabled
   cout << "Raw Total: " << uc.EvalStr(expression, false) << endl;
}
				
			
Formatted Total: $162.342525
Raw Total: 162.342525
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      '// Define some context for the expression
      uc.DefineVariable("price = 49.99")
      uc.DefineVariable("quantity = 3")
      uc.DefineConstant("TAX_RATE = 0.0825")
      
      '// Define a format for currency output
      uc.Format("DataType: Double, Def: result = '$' + result")
      
      '// Expression to calculate total price, using variables
      Dim expression = "price * quantity * (1 + TAX_RATE)"
      
      '// Evaluate with formatting enabled
      Console.WriteLine($"Formatted Total: {uc.EvalStr(expression, true)}")
      
      '// Evaluate with formatting disabled
      Console.WriteLine($"Raw Total: {uc.EvalStr(expression, false)}")
   End Sub
End Module
				
			
Formatted Total: $162.342525
Raw Total: 162.342525
Calculates simple interest by defining variables and then evaluating an expression string that uses them.

ID: 335

See: Eval
				
					using uCalcSoftware;

var uc = new uCalc();
// Define variables representing configuration or user inputs.
uc.DefineVariable("principal = 20000");
uc.DefineVariable("annual_rate = 0.0575");
uc.DefineVariable("years = 4");

// Evaluate an expression combining these variables.
var interest = uc.Eval("principal * annual_rate * years");
Console.WriteLine($"Total Interest: {interest}");
				
			
Total Interest: 4600
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   // Define variables representing configuration or user inputs.
   uc.DefineVariable("principal = 20000");
   uc.DefineVariable("annual_rate = 0.0575");
   uc.DefineVariable("years = 4");

   // Evaluate an expression combining these variables.
   auto interest = uc.Eval("principal * annual_rate * years");
   cout << "Total Interest: " << interest << endl;
}
				
			
Total Interest: 4600
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      '// Define variables representing configuration or user inputs.
      uc.DefineVariable("principal = 20000")
      uc.DefineVariable("annual_rate = 0.0575")
      uc.DefineVariable("years = 4")
      
      '// Evaluate an expression combining these variables.
      Dim interest = uc.Eval("principal * annual_rate * years")
      Console.WriteLine($"Total Interest: {interest}")
   End Sub
End Module
				
			
Total Interest: 4600
Calculates simple interest using pre-defined variables for a real-world scenario.

ID: 1181

				
					using uCalcSoftware;

var uc = new uCalc();
uc.DefineVariable("principal = 5000");
uc.DefineVariable("rate = 0.05");
uc.DefineVariable("years = 4");
Console.WriteLine($"Interest: {uc.EvalStr("principal * rate * years")}");
				
			
Interest: 1000
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   uc.DefineVariable("principal = 5000");
   uc.DefineVariable("rate = 0.05");
   uc.DefineVariable("years = 4");
   cout << "Interest: " << uc.EvalStr("principal * rate * years") << endl;
}
				
			
Interest: 1000
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      uc.DefineVariable("principal = 5000")
      uc.DefineVariable("rate = 0.05")
      uc.DefineVariable("years = 4")
      Console.WriteLine($"Interest: {uc.EvalStr("principal * rate * years")}")
   End Sub
End Module
				
			
Interest: 1000
Calculating a simple percentage for a real-world financial scenario.

ID: 1178

				
					using uCalcSoftware;

var uc = new uCalc();
// Calculate a 15% discount on a price of $75
Console.Write("Discounted price: ");
Console.WriteLine(uc.EvalStr("75 * (1 - 0.15)"));
				
			
Discounted price: 63.75
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   // Calculate a 15% discount on a price of $75
   cout << "Discounted price: ";
   cout << uc.EvalStr("75 * (1 - 0.15)") << endl;
}
				
			
Discounted price: 63.75
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      '// Calculate a 15% discount on a price of $75
      Console.Write("Discounted price: ")
      Console.WriteLine(uc.EvalStr("75 * (1 - 0.15)"))
   End Sub
End Module
				
			
Discounted price: 63.75
Capturing both parsing-stage and evaluation-stage errors to see how ErrorLocation behaves differently.

ID: 321

				
					using uCalcSoftware;

var uc = new uCalc();

static void MyErrorHandler(Handle_uCalc h) {
   var uc = new uCalc(h);
   Console.WriteLine("--- Error Captured ---");
   Console.WriteLine($"Message: {uc.Error.Message}");
   Console.WriteLine($"Symbol: '{uc.Error.Symbol}'");
   Console.WriteLine($"Location: {uc.Error.Location}");
   Console.WriteLine($"Expression: '{uc.Error.Expression}'");
}


uc.Error.AddHandler(MyErrorHandler);

Console.WriteLine("Demonstrating a PARSING error:");
uc.EvalStr("123//456");

Console.WriteLine("");
Console.WriteLine("Demonstrating an EVALUATION error:");
uc.Error.TrapOnDivideByZero = true;
uc.EvalStr("5/0");
				
			
Demonstrating a PARSING error:
--- Error Captured ---
Message: Syntax error
Symbol: '/'
Location: 3
Expression: '123//456'

Demonstrating an EVALUATION error:
--- Error Captured ---
Message: Division by 0
Symbol: ''
Location: 0
Expression: ''
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

void ucalc_call MyErrorHandler(Handle_uCalc h) {
   auto uc = uCalc(h);
   cout << "--- Error Captured ---" << endl;
   cout << "Message: " << uc.Error().Message() << endl;
   cout << "Symbol: '" << uc.Error().Symbol() << "'" << endl;
   cout << "Location: " << uc.Error().Location() << endl;
   cout << "Expression: '" << uc.Error().Expression() << "'" << endl;
}

int main() {
   uCalc uc;
   uc.Error().AddHandler(MyErrorHandler);

   cout << "Demonstrating a PARSING error:" << endl;
   uc.EvalStr("123//456");

   cout << "" << endl;
   cout << "Demonstrating an EVALUATION error:" << endl;
   uc.Error().TrapOnDivideByZero(true);
   uc.EvalStr("5/0");
}
				
			
Demonstrating a PARSING error:
--- Error Captured ---
Message: Syntax error
Symbol: '/'
Location: 3
Expression: '123//456'

Demonstrating an EVALUATION error:
--- Error Captured ---
Message: Division by 0
Symbol: ''
Location: 0
Expression: ''
				
					Imports System
Imports uCalcSoftware
Public Module Program
   
   Public Sub MyErrorHandler(ByVal h As Handle_uCalc)
      Dim uc As New uCalc(h)
      Console.WriteLine("--- Error Captured ---")
      Console.WriteLine($"Message: {uc.Error.Message}")
      Console.WriteLine($"Symbol: '{uc.Error.Symbol}'")
      Console.WriteLine($"Location: {uc.Error.Location}")
      Console.WriteLine($"Expression: '{uc.Error.Expression}'")
   End Sub
   
   Public Sub Main()
      Dim uc As New uCalc()
      uc.Error.AddHandler(AddressOf MyErrorHandler)
      
      Console.WriteLine("Demonstrating a PARSING error:")
      uc.EvalStr("123//456")
      
      Console.WriteLine("")
      Console.WriteLine("Demonstrating an EVALUATION error:")
      uc.Error.TrapOnDivideByZero = true
      uc.EvalStr("5/0")
   End Sub
End Module
				
			
Demonstrating a PARSING error:
--- Error Captured ---
Message: Syntax error
Symbol: '/'
Location: 3
Expression: '123//456'

Demonstrating an EVALUATION error:
--- Error Captured ---
Message: Division by 0
Symbol: ''
Location: 0
Expression: ''
CaseSensitive

ID: 122

				
					using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();
t.Str("start x y z finish, StArT a b c FinISH, START 1 2 3 FINISH");
var Pattern = t.Pattern("StArT {etc} FinISH");

Pattern.CaseSensitive = true;
Console.WriteLine($"CaseSensitive: {Pattern.CaseSensitive}");
Console.WriteLine("-------------------");
t.Find();
Console.WriteLine(t.Matches.Text);
Console.WriteLine("");

Pattern.CaseSensitive = false;
Console.WriteLine($"CaseSensitive: {Pattern.CaseSensitive}");
Console.WriteLine("--------------------");
t.Find();
Console.WriteLine(t.Matches.Text);
				
			
CaseSensitive: True
-------------------
StArT a b c FinISH

CaseSensitive: False
--------------------
start x y z finish
StArT a b c FinISH
START 1 2 3 FINISH
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

#define tf(IsTrue) ((IsTrue) ? "True" : "False")

int main() {
   uCalc uc;
   auto t = uc.NewTransformer();
   t.Str("start x y z finish, StArT a b c FinISH, START 1 2 3 FINISH");
   auto Pattern = t.Pattern("StArT {etc} FinISH");

   Pattern.CaseSensitive(true);
   cout << "CaseSensitive: " << tf(Pattern.CaseSensitive()) << endl;
   cout << "-------------------" << endl;
   t.Find();
   cout << t.Matches().Text() << endl;
   cout << "" << endl;

   Pattern.CaseSensitive(false);
   cout << "CaseSensitive: " << tf(Pattern.CaseSensitive()) << endl;
   cout << "--------------------" << endl;
   t.Find();
   cout << t.Matches().Text() << endl;
}
				
			
CaseSensitive: True
-------------------
StArT a b c FinISH

CaseSensitive: False
--------------------
start x y z finish
StArT a b c FinISH
START 1 2 3 FINISH
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim t = uc.NewTransformer()
      t.Str("start x y z finish, StArT a b c FinISH, START 1 2 3 FINISH")
      Dim Pattern = t.Pattern("StArT {etc} FinISH")
      
      Pattern.CaseSensitive = true
      Console.WriteLine($"CaseSensitive: {Pattern.CaseSensitive}")
      Console.WriteLine("-------------------")
      t.Find()
      Console.WriteLine(t.Matches.Text)
      Console.WriteLine("")
      
      Pattern.CaseSensitive = false
      Console.WriteLine($"CaseSensitive: {Pattern.CaseSensitive}")
      Console.WriteLine("--------------------")
      t.Find()
      Console.WriteLine(t.Matches.Text)
   End Sub
End Module
				
			
CaseSensitive: True
-------------------
StArT a b c FinISH

CaseSensitive: False
--------------------
start x y z finish
StArT a b c FinISH
START 1 2 3 FINISH
Chains `Before` and `Replace` to modify only the scheme of a URL, demonstrating the live view concept.

ID: 1270

				
					using uCalcSoftware;

var uc = new uCalc();
using (var url = new uCalc.String("http://example.com")) {
   Console.WriteLine($"Original URL: {url}");
   // Get a view of the scheme part
   var schemeView = url.Before("://");
   // Modify the view
   schemeView.Replace("http", "https");
   // The original string is updated
   Console.WriteLine($"Modified URL: {url}");
}
				
			
Original URL: http://example.com
Modified URL: https://example.com
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   {
      uCalc::String url("http://example.com");
      url.Owned(); // Causes url to be released when it goes out of scope
      cout << "Original URL: " << url << endl;
      // Get a view of the scheme part
      auto schemeView = url.Before("://");
      // Modify the view
      schemeView.Replace("http", "https");
      // The original string is updated
      cout << "Modified URL: " << url << endl;
   }
}
				
			
Original URL: http://example.com
Modified URL: https://example.com
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Using url As New uCalc.String("http://example.com")
         Console.WriteLine($"Original URL: {url}")
         '// Get a view of the scheme part
         Dim schemeView = url.Before("://")
         '// Modify the view
         schemeView.Replace("http", "https")
         '// The original string is updated
         Console.WriteLine($"Modified URL: {url}")
      End Using
   End Sub
End Module
				
			
Original URL: http://example.com
Modified URL: https://example.com
Change characters accepted as alphanumeric in expressions using ExpressionTokens() & Token()

ID: 71

				
					using uCalcSoftware;

var uc = new uCalc();
// (See alternate version of this example using ItemOf instead of ExpressionTokens)

// In this section underscore, _, and numeric digits
// are accepted as part of alphanumeric tokens
uc.DefineVariable("My_Variable = 111");
Console.WriteLine(uc.Error.Message);
uc.DefineVariable("Variable123 = 222");
Console.WriteLine(uc.Error.Message);

Console.WriteLine(uc.ExpressionTokens[TokenType.AlphaNumeric].Regex);
Console.WriteLine(uc.EvalStr("My_Variable"));
Console.WriteLine(uc.EvalStr("Variable123"));
Console.WriteLine("---");

// Now we no longer want underscore, _, or numeric digits
// to be accepted in alphanumeric tokens; only A-Z
uc.ExpressionTokens[TokenType.AlphaNumeric].Regex = "[a-zA-Z]+";

uc.DefineVariable("Other_Variable = 333");
Console.WriteLine(uc.Error.Message);
uc.DefineVariable("OtherVariable123 = 444");
Console.WriteLine(uc.Error.Message);

Console.WriteLine(uc.EvalStr("Other_Variable"));
Console.WriteLine(uc.EvalStr("OtherVariable123 "));
Console.WriteLine(uc.EvalStr("My_Variable"));
Console.WriteLine(uc.EvalStr("Variable123"));
Console.WriteLine("---");

// We restore the alphanumeric regex to support _ and numbers again
// Note: My_Variable and Variable123 remained; they were simply inaccessible
uc.ExpressionTokens[TokenType.AlphaNumeric].Regex = "[a-zA-Z_][a-zA-Z0-9_]*";
Console.WriteLine(uc.EvalStr("My_Variable"));
Console.WriteLine(uc.EvalStr("Variable123"));
				
			
No error
No error
[a-zA-Z_][a-zA-Z0-9_]*
111
222
---
Invalid definition
Invalid definition
Undefined identifier
Undefined identifier
Undefined identifier
Undefined identifier
---
111
222
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   // (See alternate version of this example using ItemOf instead of ExpressionTokens)

   // In this section underscore, _, and numeric digits
   // are accepted as part of alphanumeric tokens
   uc.DefineVariable("My_Variable = 111");
   cout << uc.Error().Message() << endl;
   uc.DefineVariable("Variable123 = 222");
   cout << uc.Error().Message() << endl;

   cout << uc.ExpressionTokens()[TokenType::AlphaNumeric].Regex() << endl;
   cout << uc.EvalStr("My_Variable") << endl;
   cout << uc.EvalStr("Variable123") << endl;
   cout << "---" << endl;

   // Now we no longer want underscore, _, or numeric digits
   // to be accepted in alphanumeric tokens; only A-Z
   uc.ExpressionTokens()[TokenType::AlphaNumeric].Regex("[a-zA-Z]+");

   uc.DefineVariable("Other_Variable = 333");
   cout << uc.Error().Message() << endl;
   uc.DefineVariable("OtherVariable123 = 444");
   cout << uc.Error().Message() << endl;

   cout << uc.EvalStr("Other_Variable") << endl;
   cout << uc.EvalStr("OtherVariable123 ") << endl;
   cout << uc.EvalStr("My_Variable") << endl;
   cout << uc.EvalStr("Variable123") << endl;
   cout << "---" << endl;

   // We restore the alphanumeric regex to support _ and numbers again
   // Note: My_Variable and Variable123 remained; they were simply inaccessible
   uc.ExpressionTokens()[TokenType::AlphaNumeric].Regex("[a-zA-Z_][a-zA-Z0-9_]*");
   cout << uc.EvalStr("My_Variable") << endl;
   cout << uc.EvalStr("Variable123") << endl;
}
				
			
No error
No error
[a-zA-Z_][a-zA-Z0-9_]*
111
222
---
Invalid definition
Invalid definition
Undefined identifier
Undefined identifier
Undefined identifier
Undefined identifier
---
111
222
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      '// (See alternate version of this example using ItemOf instead of ExpressionTokens)
      
      '// In this section underscore, _, and numeric digits
      '// are accepted as part of alphanumeric tokens
      uc.DefineVariable("My_Variable = 111")
      Console.WriteLine(uc.Error.Message)
      uc.DefineVariable("Variable123 = 222")
      Console.WriteLine(uc.Error.Message)
      
      Console.WriteLine(uc.ExpressionTokens(TokenType.AlphaNumeric).Regex)
      Console.WriteLine(uc.EvalStr("My_Variable"))
      Console.WriteLine(uc.EvalStr("Variable123"))
      Console.WriteLine("---")
      
      '// Now we no longer want underscore, _, or numeric digits
      '// to be accepted in alphanumeric tokens; only A-Z
      uc.ExpressionTokens(TokenType.AlphaNumeric).Regex = "[a-zA-Z]+"
      
      uc.DefineVariable("Other_Variable = 333")
      Console.WriteLine(uc.Error.Message)
      uc.DefineVariable("OtherVariable123 = 444")
      Console.WriteLine(uc.Error.Message)
      
      Console.WriteLine(uc.EvalStr("Other_Variable"))
      Console.WriteLine(uc.EvalStr("OtherVariable123 "))
      Console.WriteLine(uc.EvalStr("My_Variable"))
      Console.WriteLine(uc.EvalStr("Variable123"))
      Console.WriteLine("---")
      
      '// We restore the alphanumeric regex to support _ and numbers again
      '// Note: My_Variable and Variable123 remained; they were simply inaccessible
      uc.ExpressionTokens(TokenType.AlphaNumeric).Regex = "[a-zA-Z_][a-zA-Z0-9_]*"
      Console.WriteLine(uc.EvalStr("My_Variable"))
      Console.WriteLine(uc.EvalStr("Variable123"))
   End Sub
End Module
				
			
No error
No error
[a-zA-Z_][a-zA-Z0-9_]*
111
222
---
Invalid definition
Invalid definition
Undefined identifier
Undefined identifier
Undefined identifier
Undefined identifier
---
111
222
Change newline from statement separator to whitespace

ID: 220

				
					using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

t.Str("""

<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div>

""");

t.Pattern("<div>{body}</div>");

Console.WriteLine("Newline as statement separator (default)");
Console.WriteLine("----------------------------------------");
Console.WriteLine(t.Find().Matches.Text);
Console.WriteLine("");

Console.WriteLine("Newline as whitespace");
Console.WriteLine("---------------------");
t.Tokens["_token_newline"].TypeOfToken = TokenType.Whitespace;
Console.WriteLine(t.Find().Matches.Text);
				
			
Newline as statement separator (default)
----------------------------------------
<div>a b c</div>
<div>1 2 3</div>

Newline as whitespace
---------------------
<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div>
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   auto t = uc.NewTransformer();

   t.Str(R"(
<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div>
)");

   t.Pattern("<div>{body}</div>");

   cout << "Newline as statement separator (default)" << endl;
   cout << "----------------------------------------" << endl;
   cout << t.Find().Matches().Text() << endl;
   cout << "" << endl;

   cout << "Newline as whitespace" << endl;
   cout << "---------------------" << endl;
   t.Tokens()["_token_newline"].TypeOfToken(TokenType::Whitespace);
   cout << t.Find().Matches().Text() << endl;
}
				
			
Newline as statement separator (default)
----------------------------------------
<div>a b c</div>
<div>1 2 3</div>

Newline as whitespace
---------------------
<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div>
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim t = uc.NewTransformer()
      
      t.Str("
<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div>
")
      
      t.Pattern("<div>{body}</div>")
      
      Console.WriteLine("Newline as statement separator (default)")
      Console.WriteLine("----------------------------------------")
      Console.WriteLine(t.Find().Matches.Text)
      Console.WriteLine("")
      
      Console.WriteLine("Newline as whitespace")
      Console.WriteLine("---------------------")
      t.Tokens("_token_newline").TypeOfToken = TokenType.Whitespace
      Console.WriteLine(t.Find().Matches.Text)
   End Sub
End Module
				
			
Newline as statement separator (default)
----------------------------------------
<div>a b c</div>
<div>1 2 3</div>

Newline as whitespace
---------------------
<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div>
Change newline from statement separator to whitespace using TypeOfToken

ID: 221

				
					using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

t.Str("""

<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div>

""");

t.Pattern("<div>{body}</div>");
var NewLineToken = t.Tokens["_token_newline"];

Console.WriteLine("Newline as statement separator (default)");
Console.WriteLine("----------------------------------------");
Console.WriteLine(t.Find().Matches.Text);
Console.WriteLine("");

Console.WriteLine("Newline as whitespace");
Console.WriteLine("---------------------");
NewLineToken.TypeOfToken = TokenType.Whitespace;
Console.WriteLine(t.Find().Matches.Text);
				
			
Newline as statement separator (default)
----------------------------------------
<div>a b c</div>
<div>1 2 3</div>

Newline as whitespace
---------------------
<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div>
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   auto t = uc.NewTransformer();

   t.Str(R"(
<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div>
)");

   t.Pattern("<div>{body}</div>");
   auto NewLineToken = t.Tokens()["_token_newline"];

   cout << "Newline as statement separator (default)" << endl;
   cout << "----------------------------------------" << endl;
   cout << t.Find().Matches().Text() << endl;
   cout << "" << endl;

   cout << "Newline as whitespace" << endl;
   cout << "---------------------" << endl;
   NewLineToken.TypeOfToken(TokenType::Whitespace);
   cout << t.Find().Matches().Text() << endl;
}
				
			
Newline as statement separator (default)
----------------------------------------
<div>a b c</div>
<div>1 2 3</div>

Newline as whitespace
---------------------
<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div>
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim t = uc.NewTransformer()
      
      t.Str("
<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div>
")
      
      t.Pattern("<div>{body}</div>")
      Dim NewLineToken = t.Tokens("_token_newline")
      
      Console.WriteLine("Newline as statement separator (default)")
      Console.WriteLine("----------------------------------------")
      Console.WriteLine(t.Find().Matches.Text)
      Console.WriteLine("")
      
      Console.WriteLine("Newline as whitespace")
      Console.WriteLine("---------------------")
      NewLineToken.TypeOfToken = TokenType.Whitespace
      Console.WriteLine(t.Find().Matches.Text)
   End Sub
End Module
				
			
Newline as statement separator (default)
----------------------------------------
<div>a b c</div>
<div>1 2 3</div>

Newline as whitespace
---------------------
<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div>
Changing accepted tokens with ItemOf().Regex or ExpressionTokens().Token

ID: 72

				
					using uCalcSoftware;

var uc = new uCalc();
// (See alternate version of this example using ExpressionTokens instead of ItemOf)

// In this section underscore, _, and numeric digits
// are accepted as part of alphanumeric tokens
uc.DefineVariable("My_Variable = 111");
Console.WriteLine(uc.Error.Message);
uc.DefineVariable("Variable123 = 222");
Console.WriteLine(uc.Error.Message);

Console.WriteLine(uc.ItemOf("_Token_Alphanumeric").Regex);
Console.WriteLine(uc.EvalStr("My_Variable"));
Console.WriteLine(uc.EvalStr("Variable123"));
Console.WriteLine("---");

// Now we no longer want underscore, _, or numeric digits
// to be accepted in alphanumeric tokens; only A-Z
uc.ItemOf("_Token_Alphanumeric").Regex = "[a-zA-Z]+";

uc.DefineVariable("Other_Variable = 333");
Console.WriteLine(uc.Error.Message);
uc.DefineVariable("OtherVariable123 = 444");
Console.WriteLine(uc.Error.Message);

Console.WriteLine(uc.EvalStr("Other_Variable"));
Console.WriteLine(uc.EvalStr("OtherVariable123 "));
Console.WriteLine(uc.EvalStr("My_Variable"));
Console.WriteLine(uc.EvalStr("Variable123"));
Console.WriteLine("---");

//
// We restore the alphanumeric regex to support _ and numbers again
// Note: My_Variable and Variable123 remained; they were simply inaccessible
// Also: We can't use the commented line below because it has the underscore, _,
// character that we had removed.
// uc.ItemOf("_token_alphanumeric").Regex("[a-zA-Z_][a-zA-Z0-9_]*");
uc.ExpressionTokens[TokenType.AlphaNumeric].Regex = "[a-zA-Z_][a-zA-Z0-9_]*";
Console.WriteLine(uc.EvalStr("My_Variable"));
Console.WriteLine(uc.EvalStr("Variable123"));
				
			
No error
No error
[a-zA-Z_][a-zA-Z0-9_]*
111
222
---
Invalid definition
Invalid definition
Undefined identifier
Undefined identifier
Undefined identifier
Undefined identifier
---
111
222
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   // (See alternate version of this example using ExpressionTokens instead of ItemOf)

   // In this section underscore, _, and numeric digits
   // are accepted as part of alphanumeric tokens
   uc.DefineVariable("My_Variable = 111");
   cout << uc.Error().Message() << endl;
   uc.DefineVariable("Variable123 = 222");
   cout << uc.Error().Message() << endl;

   cout << uc.ItemOf("_Token_Alphanumeric").Regex() << endl;
   cout << uc.EvalStr("My_Variable") << endl;
   cout << uc.EvalStr("Variable123") << endl;
   cout << "---" << endl;

   // Now we no longer want underscore, _, or numeric digits
   // to be accepted in alphanumeric tokens; only A-Z
   uc.ItemOf("_Token_Alphanumeric").Regex("[a-zA-Z]+");

   uc.DefineVariable("Other_Variable = 333");
   cout << uc.Error().Message() << endl;
   uc.DefineVariable("OtherVariable123 = 444");
   cout << uc.Error().Message() << endl;

   cout << uc.EvalStr("Other_Variable") << endl;
   cout << uc.EvalStr("OtherVariable123 ") << endl;
   cout << uc.EvalStr("My_Variable") << endl;
   cout << uc.EvalStr("Variable123") << endl;
   cout << "---" << endl;

   //
   // We restore the alphanumeric regex to support _ and numbers again
   // Note: My_Variable and Variable123 remained; they were simply inaccessible
   // Also: We can't use the commented line below because it has the underscore, _,
   // character that we had removed.
   // uc.ItemOf("_token_alphanumeric").Regex("[a-zA-Z_][a-zA-Z0-9_]*");
   uc.ExpressionTokens()[TokenType::AlphaNumeric].Regex("[a-zA-Z_][a-zA-Z0-9_]*");
   cout << uc.EvalStr("My_Variable") << endl;
   cout << uc.EvalStr("Variable123") << endl;
}
				
			
No error
No error
[a-zA-Z_][a-zA-Z0-9_]*
111
222
---
Invalid definition
Invalid definition
Undefined identifier
Undefined identifier
Undefined identifier
Undefined identifier
---
111
222
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      '// (See alternate version of this example using ExpressionTokens instead of ItemOf)
      
      '// In this section underscore, _, and numeric digits
      '// are accepted as part of alphanumeric tokens
      uc.DefineVariable("My_Variable = 111")
      Console.WriteLine(uc.Error.Message)
      uc.DefineVariable("Variable123 = 222")
      Console.WriteLine(uc.Error.Message)
      
      Console.WriteLine(uc.ItemOf("_Token_Alphanumeric").Regex)
      Console.WriteLine(uc.EvalStr("My_Variable"))
      Console.WriteLine(uc.EvalStr("Variable123"))
      Console.WriteLine("---")
      
      '// Now we no longer want underscore, _, or numeric digits
      '// to be accepted in alphanumeric tokens; only A-Z
      uc.ItemOf("_Token_Alphanumeric").Regex = "[a-zA-Z]+"
      
      uc.DefineVariable("Other_Variable = 333")
      Console.WriteLine(uc.Error.Message)
      uc.DefineVariable("OtherVariable123 = 444")
      Console.WriteLine(uc.Error.Message)
      
      Console.WriteLine(uc.EvalStr("Other_Variable"))
      Console.WriteLine(uc.EvalStr("OtherVariable123 "))
      Console.WriteLine(uc.EvalStr("My_Variable"))
      Console.WriteLine(uc.EvalStr("Variable123"))
      Console.WriteLine("---")
      
      '//
      '// We restore the alphanumeric regex to support _ and numbers again
      '// Note: My_Variable and Variable123 remained; they were simply inaccessible
      '// Also: We can't use the commented line below because it has the underscore, _,
      '// character that we had removed.
      '// uc.ItemOf("_token_alphanumeric").Regex("[a-zA-Z_][a-zA-Z0-9_]*");
      uc.ExpressionTokens(TokenType.AlphaNumeric).Regex = "[a-zA-Z_][a-zA-Z0-9_]*"
      Console.WriteLine(uc.EvalStr("My_Variable"))
      Console.WriteLine(uc.EvalStr("Variable123"))
   End Sub
End Module
				
			
No error
No error
[a-zA-Z_][a-zA-Z0-9_]*
111
222
---
Invalid definition
Invalid definition
Undefined identifier
Undefined identifier
Undefined identifier
Undefined identifier
---
111
222
Changing an item's property

ID: 101

				
					using uCalcSoftware;

var uc = new uCalc();
var MyVar = uc.DefineVariable("x = 100");
Console.WriteLine(uc.EvalStr("x"));

uc.EvalStr("x = 200");
Console.WriteLine(uc.EvalStr("x")); // x can change here

// Locking an item prevents it from being changed
MyVar.IsProperty(ItemIs.Locked, true);

uc.EvalStr("x = 300"); // x cannot change here
Console.WriteLine(uc.EvalStr("x")); // x retains the previous value




				
			
100
200
200
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   auto MyVar = uc.DefineVariable("x = 100");
   cout << uc.EvalStr("x") << endl;

   uc.EvalStr("x = 200");
   cout << uc.EvalStr("x") << endl; // x can change here

   // Locking an item prevents it from being changed
   MyVar.IsProperty(ItemIs::Locked, true);

   uc.EvalStr("x = 300"); // x cannot change here
   cout << uc.EvalStr("x") << endl; // x retains the previous value




}
				
			
100
200
200
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim MyVar = uc.DefineVariable("x = 100")
      Console.WriteLine(uc.EvalStr("x"))
      
      uc.EvalStr("x = 200")
      Console.WriteLine(uc.EvalStr("x")) '// x can change here
      
      '// Locking an item prevents it from being changed
      MyVar.IsProperty(ItemIs.Locked, true)
      
      uc.EvalStr("x = 300") '// x cannot change here
      Console.WriteLine(uc.EvalStr("x")) '// x retains the previous value
      
      
      
      
   End Sub
End Module
				
			
100
200
200
Changing the parent uCalc object for a Transformer

ID: 160

				
					using uCalcSoftware;

var uc = new uCalc();
uc.DefineVariable("x = 1");
uc.DefineVariable("y = 2");
uc.DefineFunction("f(x) = x * 10");

var t = uc.NewTransformer();
var text = "Adding {x} and {y} gives: {x + y}. f(5) = {f(5)}";

var uNew = new uCalc();
uNew.DefineVariable("x = 111");
uNew.DefineVariable("y = 222");
uNew.DefineFunction("f(x) = x * 1000");

// Note: {@@Eval: txt} is equivalent of {@Eval: Eval(txt)}
// which is what's needed for to evaluate the expression
// resulting from the match that is not known ahead of time
t.FromTo("'{' {expr} '}'", "{@@Eval: expr}");
Console.WriteLine(t.Transform(text));

t.uCalc = uNew;
t.FromTo("'{' {expr} '}'", "{@@Eval: expr}");
Console.WriteLine(t.Transform(text));

				
			
Adding 1 and 2 gives: 3. f(5) = 50
Adding 111 and 222 gives: 333. f(5) = 5000
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   uc.DefineVariable("x = 1");
   uc.DefineVariable("y = 2");
   uc.DefineFunction("f(x) = x * 10");

   auto t = uc.NewTransformer();
   auto text = "Adding {x} and {y} gives: {x + y}. f(5) = {f(5)}";

   uCalc uNew;
   uNew.DefineVariable("x = 111");
   uNew.DefineVariable("y = 222");
   uNew.DefineFunction("f(x) = x * 1000");

   // Note: {@@Eval: txt} is equivalent of {@Eval: Eval(txt)}
   // which is what's needed for to evaluate the expression
   // resulting from the match that is not known ahead of time
   t.FromTo("'{' {expr} '}'", "{@@Eval: expr}");
   cout << t.Transform(text) << endl;

   t.uCalc(uNew);
   t.FromTo("'{' {expr} '}'", "{@@Eval: expr}");
   cout << t.Transform(text) << endl;

}
				
			
Adding 1 and 2 gives: 3. f(5) = 50
Adding 111 and 222 gives: 333. f(5) = 5000
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      uc.DefineVariable("x = 1")
      uc.DefineVariable("y = 2")
      uc.DefineFunction("f(x) = x * 10")
      
      Dim t = uc.NewTransformer()
      Dim text = "Adding {x} and {y} gives: {x + y}. f(5) = {f(5)}"
      
      Dim uNew As New uCalc()
      uNew.DefineVariable("x = 111")
      uNew.DefineVariable("y = 222")
      uNew.DefineFunction("f(x) = x * 1000")
      
      '// Note: {@@Eval: txt} is equivalent of {@Eval: Eval(txt)}
      '// which is what's needed for to evaluate the expression
      '// resulting from the match that is not known ahead of time
      t.FromTo("'{' {expr} '}'", "{@@Eval: expr}")
      Console.WriteLine(t.Transform(text))
      
      t.uCalc = uNew
      t.FromTo("'{' {expr} '}'", "{@@Eval: expr}")
      Console.WriteLine(t.Transform(text))
      
   End Sub
End Module
				
			
Adding 1 and 2 gives: 3. f(5) = 50
Adding 111 and 222 gives: 333. f(5) = 5000
Checking if a uCalc object is the default with IsDefault

ID: 75

				
					using uCalcSoftware;

var uc = new uCalc();
var Status = uc.DefineVariable("Status As Bool");
Console.WriteLine(Status.ValueBool());

var MyuCalc = new uCalc();

Status.ValueBool(MyuCalc.IsDefault);
Console.WriteLine(uc.EvalStr("$'MyuCalc is the current default? {Status}'"));

MyuCalc.IsDefault = true;
Status.ValueBool(MyuCalc.IsDefault);

Console.WriteLine(uc.EvalStr("$'MyuCalc is the current default? {Status}'"));
				
			
False
MyuCalc is the current default? false
MyuCalc is the current default? true
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

#define tf(IsTrue) ((IsTrue) ? "True" : "False")

int main() {
   uCalc uc;
   auto Status = uc.DefineVariable("Status As Bool");
   cout << tf(Status.ValueBool()) << endl;

   uCalc MyuCalc;

   Status.ValueBool(MyuCalc.IsDefault());
   cout << uc.EvalStr("$'MyuCalc is the current default? {Status}'") << endl;

   MyuCalc.IsDefault(true);
   Status.ValueBool(MyuCalc.IsDefault());

   cout << uc.EvalStr("$'MyuCalc is the current default? {Status}'") << endl;
}
				
			
False
MyuCalc is the current default? false
MyuCalc is the current default? true
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim Status = uc.DefineVariable("Status As Bool")
      Console.WriteLine(Status.ValueBool())
      
      Dim MyuCalc As New uCalc()
      
      Status.ValueBool(MyuCalc.IsDefault)
      Console.WriteLine(uc.EvalStr("$'MyuCalc is the current default? {Status}'"))
      
      MyuCalc.IsDefault = true
      Status.ValueBool(MyuCalc.IsDefault)
      
      Console.WriteLine(uc.EvalStr("$'MyuCalc is the current default? {Status}'"))
   End Sub
End Module
				
			
False
MyuCalc is the current default? false
MyuCalc is the current default? true
Checking the error code for a simple syntax error

ID: 1457

				
					using uCalcSoftware;

var uc = new uCalc();
var result = uc.Eval("MyVar * 10");
Console.WriteLine("An error has occurred!");
Console.WriteLine($"Error #: {(int)uc.Error.Code}");
Console.WriteLine($"Error Message: {uc.Error.Message}");
Console.WriteLine($"Error Location: {uc.Error.Location}");
Console.WriteLine($"Error Expression: {uc.Error.Expression}");
				
			
An error has occurred!
Error #: 258
Error Message: Undefined identifier
Error Location: 0
Error Expression: MyVar * 10
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   auto result = uc.Eval("MyVar * 10");
   cout << "An error has occurred!" << endl;
   cout << "Error #: " << (int)uc.Error().Code() << endl;
   cout << "Error Message: " << uc.Error().Message() << endl;
   cout << "Error Location: " << uc.Error().Location() << endl;
   cout << "Error Expression: " << uc.Error().Expression() << endl;
}
				
			
An error has occurred!
Error #: 258
Error Message: Undefined identifier
Error Location: 0
Error Expression: MyVar * 10
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim result = uc.Eval("MyVar * 10")
      Console.WriteLine("An error has occurred!")
      Console.WriteLine($"Error #: {CInt(uc.Error.Code)}")
      Console.WriteLine($"Error Message: {uc.Error.Message}")
      Console.WriteLine($"Error Location: {uc.Error.Location}")
      Console.WriteLine($"Error Expression: {uc.Error.Expression}")
   End Sub
End Module
				
			
An error has occurred!
Error #: 258
Error Message: Undefined identifier
Error Location: 0
Error Expression: MyVar * 10
Checking the error code for a simple syntax error using a callback.

ID: 325

				
					using uCalcSoftware;

var uc = new uCalc();

static void MyHandler(Handle_uCalc h) {
   var uc = new uCalc(h);
   // Retrieve the error code as an integer for display
   int code = (int)uc.Error.Code;
   Console.WriteLine($"Caught Error Code: {code}");

   // Compare the error code against the ErrorCode enum for logic
   if (uc.Error.Code == ErrorCode.Syntax_Error) {
      Console.WriteLine("This was a syntax error.");
   }
}


// Register the error handler
uc.Error.AddHandler(MyHandler);

// Intentionally cause a syntax error, which will trigger the handler
Console.WriteLine(uc.EvalStr("5 *"));
				
			
Caught Error Code: 257
This was a syntax error.
Syntax error
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

void ucalc_call MyHandler(Handle_uCalc h) {
   auto uc = uCalc(h);
   // Retrieve the error code as an integer for display
   int code = (int)uc.Error().Code();
   cout << "Caught Error Code: " << code << endl;

   // Compare the error code against the ErrorCode enum for logic
   if (uc.Error().Code() == ErrorCode::Syntax_Error) {
      cout << "This was a syntax error." << endl;
   }
}

int main() {
   uCalc uc;
   // Register the error handler
   uc.Error().AddHandler(MyHandler);

   // Intentionally cause a syntax error, which will trigger the handler
   cout << uc.EvalStr("5 *") << endl;
}
				
			
Caught Error Code: 257
This was a syntax error.
Syntax error
				
					Imports System
Imports uCalcSoftware
Public Module Program
   
   Public Sub MyHandler(ByVal h As Handle_uCalc)
      Dim uc As New uCalc(h)
      '// Retrieve the error code as an integer for display
      Dim code As Integer = uc.Error.Code
      Console.WriteLine($"Caught Error Code: {code}")
      
      '// Compare the error code against the ErrorCode enum for logic
      If uc.Error.Code = ErrorCode.Syntax_Error Then
         Console.WriteLine("This was a syntax error.")
      End If
   End Sub
   
   Public Sub Main()
      Dim uc As New uCalc()
      '// Register the error handler
      uc.Error.AddHandler(AddressOf MyHandler)
      
      '// Intentionally cause a syntax error, which will trigger the handler
      Console.WriteLine(uc.EvalStr("5 *"))
   End Sub
End Module
				
			
Caught Error Code: 257
This was a syntax error.
Syntax error
Checking variable types against BuiltInType

ID: 278

				
					using uCalcSoftware;

var uc = new uCalc();
// Define a variable with a specific type
uc.DefineVariable("myVar As Int16");

// Retrieve the generic Int16 type object
var typeObj = uc.DataTypeOf(BuiltInType.Integer_16);

// Check if the variable's type matches Int16
if (uc.ItemOf("myVar").DataType.BuiltInTypeEnum == typeObj.BuiltInTypeEnum) {
   Console.WriteLine("Variable 'myVar' is an Int16.");
} else {
   Console.WriteLine("Type mismatch.");
}
				
			
Variable 'myVar' is an Int16.
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   // Define a variable with a specific type
   uc.DefineVariable("myVar As Int16");

   // Retrieve the generic Int16 type object
   auto typeObj = uc.DataTypeOf(BuiltInType::Integer_16);

   // Check if the variable's type matches Int16
   if (uc.ItemOf("myVar").DataType().BuiltInTypeEnum() == typeObj.BuiltInTypeEnum()) {
      cout << "Variable 'myVar' is an Int16." << endl;
   } else {
      cout << "Type mismatch." << endl;
   }
}
				
			
Variable 'myVar' is an Int16.
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      '// Define a variable with a specific type
      uc.DefineVariable("myVar As Int16")
      
      '// Retrieve the generic Int16 type object
      Dim typeObj = uc.DataTypeOf(BuiltInType.Integer_16)
      
      '// Check if the variable's type matches Int16
      If uc.ItemOf("myVar").DataType.BuiltInTypeEnum = typeObj.BuiltInTypeEnum Then
         Console.WriteLine("Variable 'myVar' is an Int16.")
      Else
         Console.WriteLine("Type mismatch.")
      End If
   End Sub
End Module
				
			
Variable 'myVar' is an Int16.
Checks for the existence of a required header in a string.

ID: 1341

				
					using uCalcSoftware;

var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
   var text_ok = "Header: OK";
   var text_fail = "Header: ERROR";

   // This rule only matches if the status is "OK"
   t.Pattern("Header: OK");

   // Find() returns the transformer, so we can chain Matches().Count()
   if (t.SetText(text_ok).Find().Matches.Count() > 0) {
      Console.WriteLine("text_ok is valid.");
   }

   if (t.SetText(text_fail).Find().Matches.Count() == 0) {
      Console.WriteLine("text_fail is invalid.");
   }
}
				
			
text_ok is valid.
text_fail is invalid.
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   {
      uCalc::Transformer t;
      t.Owned(); // Causes t to be released when it goes out of scope
      auto text_ok = "Header: OK";
      auto text_fail = "Header: ERROR";

      // This rule only matches if the status is "OK"
      t.Pattern("Header: OK");

      // Find() returns the transformer, so we can chain Matches().Count()
      if (t.SetText(text_ok).Find().Matches().Count() > 0) {
         cout << "text_ok is valid." << endl;
      }

      if (t.SetText(text_fail).Find().Matches().Count() == 0) {
         cout << "text_fail is invalid." << endl;
      }
   }
}
				
			
text_ok is valid.
text_fail is invalid.
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Using t As New uCalc.Transformer()
         Dim text_ok = "Header: OK"
         Dim text_fail = "Header: ERROR"
         
         '// This rule only matches if the status is "OK"
         t.Pattern("Header: OK")
         
         '// Find() returns the transformer, so we can chain Matches().Count()
         If t.SetText(text_ok).Find().Matches.Count() > 0 Then
            Console.WriteLine("text_ok is valid.")
         End If
         
         If t.SetText(text_fail).Find().Matches.Count() = 0 Then
            Console.WriteLine("text_fail is invalid.")
         End If
      End Using
   End Sub
End Module
				
			
text_ok is valid.
text_fail is invalid.
Checks for the existence of a required header in a string.

ID: 1449

				
					using uCalcSoftware;

var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
   var text_ok = "Header: OK";
   var text_fail = "Header: ERROR";

   // This rule only matches if the status is "OK"
   t.Pattern("Header: OK");

   // Find() returns the transformer, so we can chain Matches().Count()
   if (t.SetText(text_ok).Find().Matches.Count() > 0) {
      Console.WriteLine("text_ok is valid.");
   }

   if (t.SetText(text_fail).Find().Matches.Count() == 0) {
      Console.WriteLine("text_fail is invalid.");
   }
}
				
			
text_ok is valid.
text_fail is invalid.
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   {
      uCalc::Transformer t;
      t.Owned(); // Causes t to be released when it goes out of scope
      auto text_ok = "Header: OK";
      auto text_fail = "Header: ERROR";

      // This rule only matches if the status is "OK"
      t.Pattern("Header: OK");

      // Find() returns the transformer, so we can chain Matches().Count()
      if (t.SetText(text_ok).Find().Matches().Count() > 0) {
         cout << "text_ok is valid." << endl;
      }

      if (t.SetText(text_fail).Find().Matches().Count() == 0) {
         cout << "text_fail is invalid." << endl;
      }
   }
}
				
			
text_ok is valid.
text_fail is invalid.
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Using t As New uCalc.Transformer()
         Dim text_ok = "Header: OK"
         Dim text_fail = "Header: ERROR"
         
         '// This rule only matches if the status is "OK"
         t.Pattern("Header: OK")
         
         '// Find() returns the transformer, so we can chain Matches().Count()
         If t.SetText(text_ok).Find().Matches.Count() > 0 Then
            Console.WriteLine("text_ok is valid.")
         End If
         
         If t.SetText(text_fail).Find().Matches.Count() = 0 Then
            Console.WriteLine("text_fail is invalid.")
         End If
      End Using
   End Sub
End Module
				
			
text_ok is valid.
text_fail is invalid.
Comprehensive demonstration of Count() across arrays, functions with different parameter types, and operators.

ID: 611

				
					using uCalcSoftware;

var uc = new uCalc();

static void MyAverage(uCalc.Callback cb) {
   double Total = 0;
   for (int x = 1; x <= cb.ArgCount(); x++) {
      Total = Total + cb.Arg(x);
   }
   cb.Return(Total / cb.ArgCount());
}

var MyArrayA = uc.DefineVariable("MyArrayA[] = {10, 20, 30, 40, 50}");
var MyArrayB = uc.DefineVariable("MyArrayB[15]");
var FunctionA = uc.DefineFunction("FuncA(x, y, z) = x + y + z");
var FunctionB = uc.DefineFunction("FuncB(x, y, a = 12, b = 34) = x+y+a+b");
var FunctionC = uc.DefineFunction("FuncC(x, y ...)", MyAverage);
var FunctionD = uc.DefineFunction("FuncD() = 1+1");

Console.WriteLine($"Elements in array (from initializer): {MyArrayA.Count}");
Console.WriteLine($"Elements in array (from size): {MyArrayB.Count}");
Console.WriteLine($"Parameters in FuncA() (fixed): {FunctionA.Count}");
Console.WriteLine($"Parameters in FuncB() (with optional): {FunctionB.Count}");
Console.WriteLine($"Parameters in FuncC() (variadic): {FunctionC.Count}");
Console.WriteLine($"Parameters in FuncD() (none): {FunctionD.Count}");
Console.WriteLine($"Operands in '!' operator (postfix): {uc.ItemOf("!").Count}");
Console.WriteLine($"Operands in '>' operator (infix): {uc.ItemOf(">").Count}");
				
			
Elements in array (from initializer): 5
Elements in array (from size): 15
Parameters in FuncA() (fixed): 3
Parameters in FuncB() (with optional): 4
Parameters in FuncC() (variadic): -1
Parameters in FuncD() (none): 0
Operands in '!' operator (postfix): 1
Operands in '>' operator (infix): 2
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

void ucalc_call MyAverage(uCalcBase::Callback cb) {
   double Total = 0;
   for (int x = 1; x <= cb.ArgCount(); x++) {
      Total = Total + cb.Arg(x);
   }
   cb.Return(Total / cb.ArgCount());
}
int main() {
   uCalc uc;
   auto MyArrayA = uc.DefineVariable("MyArrayA[] = {10, 20, 30, 40, 50}");
   auto MyArrayB = uc.DefineVariable("MyArrayB[15]");
   auto FunctionA = uc.DefineFunction("FuncA(x, y, z) = x + y + z");
   auto FunctionB = uc.DefineFunction("FuncB(x, y, a = 12, b = 34) = x+y+a+b");
   auto FunctionC = uc.DefineFunction("FuncC(x, y ...)", MyAverage);
   auto FunctionD = uc.DefineFunction("FuncD() = 1+1");

   cout << "Elements in array (from initializer): " << MyArrayA.Count() << endl;
   cout << "Elements in array (from size): " << MyArrayB.Count() << endl;
   cout << "Parameters in FuncA() (fixed): " << FunctionA.Count() << endl;
   cout << "Parameters in FuncB() (with optional): " << FunctionB.Count() << endl;
   cout << "Parameters in FuncC() (variadic): " << FunctionC.Count() << endl;
   cout << "Parameters in FuncD() (none): " << FunctionD.Count() << endl;
   cout << "Operands in '!' operator (postfix): " << uc.ItemOf("!").Count() << endl;
   cout << "Operands in '>' operator (infix): " << uc.ItemOf(">").Count() << endl;
}
				
			
Elements in array (from initializer): 5
Elements in array (from size): 15
Parameters in FuncA() (fixed): 3
Parameters in FuncB() (with optional): 4
Parameters in FuncC() (variadic): -1
Parameters in FuncD() (none): 0
Operands in '!' operator (postfix): 1
Operands in '>' operator (infix): 2
				
					Imports System
Imports uCalcSoftware
Public Module Program
   
   Public Sub MyAverage(ByVal cb As uCalc.Callback)
      Dim Total As Double = 0
      For x  As Integer = 1 To cb.ArgCount()
         Total = Total + cb.Arg(x)
      Next
      cb.Return(Total / cb.ArgCount())
   End Sub
   Public Sub Main()
      Dim uc As New uCalc()
      Dim MyArrayA = uc.DefineVariable("MyArrayA[] = {10, 20, 30, 40, 50}")
      Dim MyArrayB = uc.DefineVariable("MyArrayB[15]")
      Dim FunctionA = uc.DefineFunction("FuncA(x, y, z) = x + y + z")
      Dim FunctionB = uc.DefineFunction("FuncB(x, y, a = 12, b = 34) = x+y+a+b")
      Dim FunctionC = uc.DefineFunction("FuncC(x, y ...)", AddressOf MyAverage)
      Dim FunctionD = uc.DefineFunction("FuncD() = 1+1")
      
      Console.WriteLine($"Elements in array (from initializer): {MyArrayA.Count}")
      Console.WriteLine($"Elements in array (from size): {MyArrayB.Count}")
      Console.WriteLine($"Parameters in FuncA() (fixed): {FunctionA.Count}")
      Console.WriteLine($"Parameters in FuncB() (with optional): {FunctionB.Count}")
      Console.WriteLine($"Parameters in FuncC() (variadic): {FunctionC.Count}")
      Console.WriteLine($"Parameters in FuncD() (none): {FunctionD.Count}")
      Console.WriteLine($"Operands in '!' operator (postfix): {uc.ItemOf("!").Count}")
      Console.WriteLine($"Operands in '>' operator (infix): {uc.ItemOf(">").Count}")
   End Sub
End Module
				
			
Elements in array (from initializer): 5
Elements in array (from size): 15
Parameters in FuncA() (fixed): 3
Parameters in FuncB() (with optional): 4
Parameters in FuncC() (variadic): -1
Parameters in FuncD() (none): 0
Operands in '!' operator (postfix): 1
Operands in '>' operator (infix): 2
Converting a single line of legacy variable declaration syntax to a modern equivalent.

ID: 1376

				
					using uCalcSoftware;

var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
   // Rule to convert legacy variable declaration
   t.FromTo("LET {@Alpha:var} = {val}", "var {var} = {val};");
   Console.WriteLine(t.Transform("LET X = 100"));
}
				
			
var X = 100;
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   {
      uCalc::Transformer t;
      t.Owned(); // Causes t to be released when it goes out of scope
      // Rule to convert legacy variable declaration
      t.FromTo("LET {@Alpha:var} = {val}", "var {var} = {val};");
      cout << t.Transform("LET X = 100") << endl;
   }
}
				
			
var X = 100;
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Using t As New uCalc.Transformer()
         '// Rule to convert legacy variable declaration
         t.FromTo("LET {@Alpha:var} = {val}", "var {var} = {val};")
         Console.WriteLine(t.Transform("LET X = 100"))
      End Using
   End Sub
End Module
				
			
var X = 100;
Converting from Celsius to Fahrenheit with the Transformer

ID: 174

				
					using uCalcSoftware;

var uc = new uCalc();
var t = uc.NewTransformer();

// Define the pattern first
t.FromTo("Temperature: {temp} C", "temperature: {@Eval: Double(temp) * 1.8 + 32} F");

// Perform the Transform() operation
Console.WriteLine(t.Transform("Here is the temperature: 22.5 C"));
				
			
Here is the temperature: 72.5 F
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   auto t = uc.NewTransformer();

   // Define the pattern first
   t.FromTo("Temperature: {temp} C", "temperature: {@Eval: Double(temp) * 1.8 + 32} F");

   // Perform the Transform() operation
   cout << t.Transform("Here is the temperature: 22.5 C") << endl;
}
				
			
Here is the temperature: 72.5 F
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim t = uc.NewTransformer()
      
      '// Define the pattern first
      t.FromTo("Temperature: {temp} C", "temperature: {@Eval: Double(temp) * 1.8 + 32} F")
      
      '// Perform the Transform() operation
      Console.WriteLine(t.Transform("Here is the temperature: 22.5 C"))
   End Sub
End Module
				
			
Here is the temperature: 72.5 F
Converting quoted strings into XML-style elements by stripping the original quotes.

ID: 895

See: {@String}
				
					using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
// Use {s(1)} to get just the text inside the quotes
t.FromTo("msg = {@String:s}", "<message>{s(1)}</message>");

string input = """
msg = "Welcome to uCalc!"
""";
Console.WriteLine(t.Transform(input));
				
			
<message>Welcome to uCalc!</message>
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   uCalc::Transformer t;
   // Use {s(1)} to get just the text inside the quotes
   t.FromTo("msg = {@String:s}", "<message>{s(1)}</message>");

   string input = R"(msg = "Welcome to uCalc!")";
   cout << t.Transform(input) << endl;
}
				
			
<message>Welcome to uCalc!</message>
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim t As New uCalc.Transformer()
      '// Use {s(1)} to get just the text inside the quotes
      t.FromTo("msg = {@String:s}", "<message>{s(1)}</message>")
      
      Dim input As String = "msg = ""Welcome to uCalc!"""
      Console.WriteLine(t.Transform(input))
   End Sub
End Module
				
			
<message>Welcome to uCalc!</message>
Converting single-quoted strings to double-quoted ones by targeting the delimiters.

ID: 888

See: {@sq}
				
					using uCalcSoftware;

var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("{@sq}", """
"
""");

Console.WriteLine(t.Transform("print 'Hello'"));
				
			
print "Hello"
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   uCalc::Transformer t;
   t.FromTo("{@sq}", R"(")");

   cout << t.Transform("print 'Hello'") << endl;
}
				
			
print "Hello"
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      Dim t As New uCalc.Transformer()
      t.FromTo("{@sq}", """")
      
      Console.WriteLine(t.Transform("print 'Hello'"))
   End Sub
End Module
				
			
print "Hello"
Core VB.NET idioms: `Using` for lifetime management, property syntax, and implicit string conversions.

ID: 815

See: VB
				
					using uCalcSoftware;

var uc = new uCalc();


// This example is meant for VB.NET only
Console.WriteLine("Description: My VB.NET uCalc instance");
Console.WriteLine("Transformer Text: Hello Again");
Console.WriteLine("Transformer Text: Hello Again");

				
			
Description: My VB.NET uCalc instance
Transformer Text: Hello Again
Transformer Text: Hello Again
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;


   // This example is meant for VB.NET only
   cout << "Description: My VB.NET uCalc instance" << endl;
   cout << "Transformer Text: Hello Again" << endl;
   cout << "Transformer Text: Hello Again" << endl;

}
				
			
Description: My VB.NET uCalc instance
Transformer Text: Hello Again
Transformer Text: Hello Again
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      
      ' 1. Automatic resource management with 'Using '
Using u = New uCalc()
    ' 2. Property syntax for setting the description
    u.Description = "My VB.NET uCalc instance"
         Console.WriteLine($"Description: {u.Description}")
         
         ' 3. Implicit String conversion for Transformer.Text
    Dim t As New uCalc.Transformer()
    t.Text = "Hello World" ' Standard assignment
         t = "Hello Again"    ' Implicit conversion assignment
         Console.WriteLine($"Transformer Text: {t.Text}")
         Console.WriteLine($"Transformer Text: {t}")
      End Using
      
      
   End Sub
End Module
				
			
Description: My VB.NET uCalc instance
Transformer Text: Hello Again
Transformer Text: Hello Again
Creates a custom `IIf` function to demonstrate basic lazy evaluation. The division-by-zero error in the unevaluated branch is safely ignored.

ID: 1229

				
					using uCalcSoftware;

var uc = new uCalc();

static void MyIIf(uCalc.Callback cb) {
   var condition = cb.ArgBool(1);
   var thenPart = cb.ArgExpr(2);
   var elsePart = cb.ArgExpr(3);

   if (condition) {
      cb.Return(thenPart.Evaluate());
   } else {
      cb.Return(elsePart.Evaluate());
   }
}

uc.DefineFunction("MyIIf(cond As Bool, ByExpr thenExpr, ByExpr elseExpr)", MyIIf);

// The 'else' branch contains 1/0, but since the condition is true,
// it is never evaluated.
Console.WriteLine(uc.Eval("MyIIf(10 > 5, 100, 1/0)"));

// The 'then' branch contains 1/0, but it is never evaluated.
Console.WriteLine(uc.Eval("MyIIf(10 < 5, 1/0, 200)"));
				
			
100
200
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

void ucalc_call MyIIf(uCalcBase::Callback cb) {
   auto condition = cb.ArgBool(1);
   auto thenPart = cb.ArgExpr(2);
   auto elsePart = cb.ArgExpr(3);

   if (condition) {
      cb.Return(thenPart.Evaluate());
   } else {
      cb.Return(elsePart.Evaluate());
   }
}
int main() {
   uCalc uc;
   uc.DefineFunction("MyIIf(cond As Bool, ByExpr thenExpr, ByExpr elseExpr)", MyIIf);

   // The 'else' branch contains 1/0, but since the condition is true,
   // it is never evaluated.
   cout << uc.Eval("MyIIf(10 > 5, 100, 1/0)") << endl;

   // The 'then' branch contains 1/0, but it is never evaluated.
   cout << uc.Eval("MyIIf(10 < 5, 1/0, 200)") << endl;
}
				
			
100
200
				
					Imports System
Imports uCalcSoftware
Public Module Program
   
   Public Sub MyIIf(ByVal cb As uCalc.Callback)
      Dim condition = cb.ArgBool(1)
      Dim thenPart = cb.ArgExpr(2)
      Dim elsePart = cb.ArgExpr(3)
      
      If condition Then
         cb.Return(thenPart.Evaluate())
      Else
         cb.Return(elsePart.Evaluate())
      End If
   End Sub
   Public Sub Main()
      Dim uc As New uCalc()
      uc.DefineFunction("MyIIf(cond As Bool, ByExpr thenExpr, ByExpr elseExpr)", AddressOf MyIIf)
      
      '// The 'else' branch contains 1/0, but since the condition is true,
      '// it is never evaluated.
      Console.WriteLine(uc.Eval("MyIIf(10 > 5, 100, 1/0)"))
      
      '// The 'then' branch contains 1/0, but it is never evaluated.
      Console.WriteLine(uc.Eval("MyIIf(10 < 5, 1/0, 200)"))
   End Sub
End Module
				
			
100
200
Creates a domain-specific currency conversion syntax using the ExpressionTransformer, the correct tool for multi-word patterns.

ID: 1225

				
					using uCalcSoftware;

var uc = new uCalc();
// Use the ExpressionTransformer for multi-word syntax.
var t = uc.ExpressionTransformer;

// Note: Captured variables are passed to @Eval as text
// Double() converts the text to Double a precision value
uc.Format("Result = Format('{:.2f}', Double(Result))", uc.DataTypeOf("Double"));
t.FromTo("{@Number:amount} USD to EUR", "({@Eval: Double(amount) * 0.92})");
t.FromTo("{@Number:amount} EUR to USD", "({@Eval: Double(amount) / 0.92})");

Console.WriteLine($"100 USD is approx. {uc.EvalStr("100 USD to EUR")} EUR");
Console.WriteLine($"120 EUR is approx. {uc.EvalStr("120 EUR to USD")} USD");
				
			
100 USD is approx. 92.00 EUR
120 EUR is approx. 130.43 USD
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   // Use the ExpressionTransformer for multi-word syntax.
   auto t = uc.ExpressionTransformer();

   // Note: Captured variables are passed to @Eval as text
   // Double() converts the text to Double a precision value
   uc.Format("Result = Format('{:.2f}', Double(Result))", uc.DataTypeOf("Double"));
   t.FromTo("{@Number:amount} USD to EUR", "({@Eval: Double(amount) * 0.92})");
   t.FromTo("{@Number:amount} EUR to USD", "({@Eval: Double(amount) / 0.92})");

   cout << "100 USD is approx. " << uc.EvalStr("100 USD to EUR") << " EUR" << endl;
   cout << "120 EUR is approx. " << uc.EvalStr("120 EUR to USD") << " USD" << endl;
}
				
			
100 USD is approx. 92.00 EUR
120 EUR is approx. 130.43 USD
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      '// Use the ExpressionTransformer for multi-word syntax.
      Dim t = uc.ExpressionTransformer
      
      '// Note: Captured variables are passed to @Eval as text
      '// Double() converts the text to Double a precision value
      uc.Format("Result = Format('{:.2f}', Double(Result))", uc.DataTypeOf("Double"))
      t.FromTo("{@Number:amount} USD to EUR", "({@Eval: Double(amount) * 0.92})")
      t.FromTo("{@Number:amount} EUR to USD", "({@Eval: Double(amount) / 0.92})")
      
      Console.WriteLine($"100 USD is approx. {uc.EvalStr("100 USD to EUR")} EUR")
      Console.WriteLine($"120 EUR is approx. {uc.EvalStr("120 EUR to USD")} USD")
   End Sub
End Module
				
			
100 USD is approx. 92.00 EUR
120 EUR is approx. 130.43 USD
Creating a clone of a uCalc object

ID: 59

See: Clone
				
					using uCalcSoftware;

var uc = new uCalc();

uc.DefineVariable("MyVar = 100");
uc.DefineFunction("MyFunc(x) = x + 1");

var Cloned_uc = uc.Clone();

Console.WriteLine(uc.EvalStr("MyVar"));
Console.WriteLine(uc.EvalStr("MyFunc(10)"));

Console.WriteLine(Cloned_uc.EvalStr("MyVar"));
Console.WriteLine(Cloned_uc.EvalStr("MyFunc(10)"));

Cloned_uc.Eval("MyVar = 200");
Cloned_uc.DefineFunction("OtherFunc(x) = x * 10");

Console.WriteLine(uc.EvalStr("MyVar"));
Console.WriteLine(uc.EvalStr("OtherFunc(5)"));

Console.WriteLine(Cloned_uc.EvalStr("MyVar"));
Console.WriteLine(Cloned_uc.EvalStr("OtherFunc(5)"));
				
			
100
11
100
11
100
Undefined identifier
200
50
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;

   uc.DefineVariable("MyVar = 100");
   uc.DefineFunction("MyFunc(x) = x + 1");

   auto Cloned_uc = uc.Clone();

   cout << uc.EvalStr("MyVar") << endl;
   cout << uc.EvalStr("MyFunc(10)") << endl;

   cout << Cloned_uc.EvalStr("MyVar") << endl;
   cout << Cloned_uc.EvalStr("MyFunc(10)") << endl;

   Cloned_uc.Eval("MyVar = 200");
   Cloned_uc.DefineFunction("OtherFunc(x) = x * 10");

   cout << uc.EvalStr("MyVar") << endl;
   cout << uc.EvalStr("OtherFunc(5)") << endl;

   cout << Cloned_uc.EvalStr("MyVar") << endl;
   cout << Cloned_uc.EvalStr("OtherFunc(5)") << endl;
}
				
			
100
11
100
11
100
Undefined identifier
200
50
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      
      uc.DefineVariable("MyVar = 100")
      uc.DefineFunction("MyFunc(x) = x + 1")
      
      Dim Cloned_uc = uc.Clone()
      
      Console.WriteLine(uc.EvalStr("MyVar"))
      Console.WriteLine(uc.EvalStr("MyFunc(10)"))
      
      Console.WriteLine(Cloned_uc.EvalStr("MyVar"))
      Console.WriteLine(Cloned_uc.EvalStr("MyFunc(10)"))
      
      Cloned_uc.Eval("MyVar = 200")
      Cloned_uc.DefineFunction("OtherFunc(x) = x * 10")
      
      Console.WriteLine(uc.EvalStr("MyVar"))
      Console.WriteLine(uc.EvalStr("OtherFunc(5)"))
      
      Console.WriteLine(Cloned_uc.EvalStr("MyVar"))
      Console.WriteLine(Cloned_uc.EvalStr("OtherFunc(5)"))
   End Sub
End Module
				
			
100
11
100
11
100
Undefined identifier
200
50