# All Examples

### Example ID: 1

**Description:** Adding an error handler callback

**Code:**
```pseudocode
[head]
[callback:u MyErrorHandler]
wl("An error has occurred!")
wl("Error #: ", [c](int)uc.@Error().@Code()[/c][vb]CInt(uc.@Error().@Code())[/vb])
wl("Error Message: ", uc.@Error().@Message())
wl("Error Symbol: ", uc.@Error().@Symbol())
wl("Error Location: ", uc.@Error().@Location())
wl("Error Expression: ", uc.@Error().@Expression())
[/callback]

[body]
uc.@Error().AddHandler(MyErrorHandler);
wl(uc.EvalStr("123+"))
wl("")

uc.@Error().@TrapOnDivideByZero(true);
wl(uc.EvalStr("5/0"))
```

**Output:**
```
An error has occurred!
Error #: 257
Error Message: Syntax error
Error Symbol: +
Error Location: 3
Error Expression: 123+
Syntax error

An error has occurred!
Error #: 8
Error Message: Division by 0
Error Symbol: 
Error Location: 0
Error Expression: 
Division by 0
```

---

### Example ID: 2

**Description:** Getting data type object with DataTypeOf

**Code:**
```pseudocode
wl(uc.DataTypeOf(BuiltInType::Integer_8u).ToString("-1"))
wl(uc.DataTypeOf(BuiltInType::Integer_16u).ToString("-1"))
wl(uc.DataTypeOf(BuiltInType::Boolean).ToString("-1"))
wl(uc.DataTypeOf(BuiltInType::String).ToString("-1"))

wl(uc.DataTypeOf(BuiltInType::Integer_8u).@Name())
wl(uc.DataTypeOf(BuiltInType::Integer_32).@ByteSize())
```

**Output:**
```
255
65535
true
-1
int8u
4
```

---

### Example ID: 3

**Description:** Returning the data type of an expression

**Code:**
```pseudocode
wl(uc.DataTypeOf("10 + 20 - 3").@Name())
wl(uc.DataTypeOf(" 'What type ' + 'is this?' ").@Name())
wl(uc.DataTypeOf("3 < 10").@Name())
wl(uc.DataTypeOf("5 + 7 * #i").@Name())
wl("---")

uc.DefineFunction("func(x) as string = 'Hello' * 3");
wl(uc.DataTypeOf("func").@Name())
wl(uc.DataTypeOf("Int").@Name())
wl(uc.DataTypeOf("NonExistantType").@Name()) // Empty string
wl(uc.DataTypeOf("&&").@Name())


```

**Output:**
```
double
string
bool
complex
---
string
int

bool
```

---

### Example ID: 4

**Description:** Setting/retrieving default data type

**Code:**
```pseudocode
// Check default data type
wl(uc.@DefaultDataType().@Name())

// This examples shows setting the default data type in 3
// different ways: by BuiltInType enum, DataType ojbect,
// or data type by name (string)

// Change default default data type
uc.@DefaultDataType(uc.DataTypeOf(BuiltInType::Integer_16));
wl(uc.@DefaultDataType().@Name())

// Test new default (returns integers instead of double)

uc.DefineFunction("ff(x, y) = (x + y)/3");
// same as ff(x As int16, y As int16) As int16 = ...

uc.DefineFunction("gg(x) = x*100");
// same as gg(x As int16) As int16 = ...

wl(uc.Eval("ff(4, 12)"))
wl(uc.Eval("gg(6.1)"))

uc.SetDefaultDataType("Single");
wl(uc.@DefaultDataType().@Name())

// Change back to original default (double)
uc.SetDefaultDataType(BuiltInType::Float_Double);

// Verify that default is now double
wl(uc.@DefaultDataType().@Name())
```

**Output:**
```
double
int16
5
600
single
double
```

---

### Example ID: 5

**Description:** Defining another function using the same callback address of existing one

**Code:**
```pseudocode
uc.DefineFunction("MyRound(x)", uc.ItemOf("Floor").@FunctionAddress());
wl(uc.Eval("MyRound(2.5)"))

uc.ItemOf("MyRound").SetFunctionAddress(uc.ItemOf("Ceil").@FunctionAddress());
wl(uc.Eval("MyRound(2.5)"))
```

**Output:**
```
2
3
```

---

### Example ID: 6

**Description:** How to define a constant, variable, operator, function, output format, and token with Define()

**Code:**
```pseudocode
wl("------ Basic examples -------")
uc.Define("Function: f(x, y) = x + y");
uc.Define("Operator: {x} %% {y} = x * y");
uc.Define("Variable: MyVar = 123");

wl(uc.Eval("f(5, 10)"))
wl(uc.Eval("5 %% 10"))
wl(uc.Eval("MyVar * 100"))

// End users can also call Define()
wl("------ End user definition -------")
uc.Eval("Define('Function: ff(x) = x * 1000')");
wl(uc.Eval("ff(987)"))

wl("------ Boolean format -------")
wl(uc.EvalStr("1 < 2"))
wl(uc.EvalStr("1 > 2"))
wl(uc.EvalStr("Int(1 < 2)"))
wl(uc.EvalStr("(True Or False) And (True And False)"))
uc.Define("Boolean: 55, TotallyTrue, CompletelyFalse");
wl(uc.EvalStr("1 < 2"))
wl(uc.EvalStr("1 > 2"))
wl(uc.EvalStr("Int(1 < 2)"))
wl(uc.EvalStr("(TotallyTrue Or CompletelyFalse) And (TotallyTrue And CompletelyFalse)"))

// Format - configures the formatting for the output given by EvalStr
wl("------ Format -------")
uc.Define("Format: Result = 'Answer: <' + Result + '>'");
uc.Define("Format: String, val = 'String Value --> ' + val");
wl(uc.EvalStr("1+2"))
wl(uc.EvalStr("'Hello ' + 'world!'"))
var Additional = uc.Define("Format: ret = 'Additional format: ' + ret");
wl(uc.EvalStr("1+2"))
uc.Define("Format: InsertAt: 0, result = 'The ' + result");
wl(uc.EvalStr("1+2"))
Additional.Release();
wl(uc.EvalStr("1+2"))
uc.FormatRemove();

// Bootstrap - builds new def on top of existing one
wl("------ Bootstrap -------")
wl(uc.EvalStr("Hex(123)")) // uses "built-in" version of Hex()
var MyHex = uc.Define("Bootstrap ~~ Function: Hex(number As Int) As String = '0x' + UCase(Hex(number))");
wl(uc.EvalStr("Hex(123)"))
MyHex.Release();
wl(uc.EvalStr("Hex(123)"))

// Overwrite - useful for spreadsheet-like functionality
wl("------ Overwrite -------")
uc.Define("Overwrite ~~ Func: SpreadsheetCell_A1() = 5");
uc.Define("Overwrite ~~ Func: SpreadsheetCell_B2() = SpreadsheetCell_A1() * 10");
uc.Define("Overwrite ~~ Func: SpreadsheetCell_C3() = SpreadsheetCell_A1() + SpreadsheetCell_B2()");
wl(uc.Eval("SpreadsheetCell_A1()"))
wl(uc.Eval("SpreadsheetCell_B2()"))
wl(uc.Eval("SpreadsheetCell_C3()"))
// SpreadsheetCell_C3() will be affected by the definition changes of SpreadsheetCell_A1() and  SpreadsheetCell_B3()
uc.Define("Overwrite ~~ Func: SpreadsheetCell_B2() = SpreadsheetCell_A1() * 100");
uc.Define("Overwrite ~~ Func: SpreadsheetCell_A1() = 25");
wl("-------")
// Note: Empty parenthesis are optional for functions with no parameters
wl(uc.Eval("SpreadsheetCell_A1"))
wl(uc.Eval("SpreadsheetCell_B2"))
wl(uc.Eval("SpreadsheetCell_C3"))

// Lock
wl("------ Lock -------")
uc.Define("Variable: xy = 555");
uc.Define("Lock ~~ Variable: pi = 3.14"); // like using DefineConstant()
wl(uc.EvalStr("xy"))
wl(uc.EvalStr("pi"))
wl(uc.EvalStr("xy = 222")) // This variable is being changed
wl(uc.EvalStr("pi = 3.14159")) // This one is locked and cannot be changed
wl(uc.EvalStr("xy")) // Returns the new value of xy
wl(uc.EvalStr("pi")) // pi did not change; returns original value
wl("-------")
uc.Define("Function: f1(x) = x + 100");
uc.Define("Lock ~~ Function: f2(x) = x + 200"); // End-user can't change f2
wl(uc.Eval("f1(5)"))
wl(uc.Eval("f2(5)"))
uc.Eval("Define('Function: f1(x) = x + 300')");
uc.Eval("Define('Function: f2(x) = x + 400')"); // This re-definition is ignored
wl(uc.Eval("f1(5)"))
wl(uc.Eval("f2(5)"))

// Tokens
wl("------ Tokens -------")
wl(uc.EvalStr("5 + 4 // This comment causes an error"));
wl(uc.EvalStr("5 + /* comment not recognized yet */ 10"))
uc.Define("TokenType: Whitespace ~~ Token: //.*"); // // C-style to end-of-line comment 
uc.Define("TokenType: Whitespace ~~ Token: /[*].*?[*]/"); // /* C-style enclosed comment */
wl(uc.EvalStr("5 + 4 // This comment will be ignored"));
wl(uc.EvalStr("5 + /* comment ignored */ 10"))

// Precedence
wl("------ Precedence -------")
uc.Define("Precedence: 1    ~~ Operator: {a As Int32} OpA {b As Int32} = a + b");
uc.Define("Precedence: 1000 ~~ Operator: {a As Int32} OpB {b As Int32} = a + b");
wl(uc.Eval("5 OpA 4 * 10"))
wl(uc.Eval("5 OpB 4 * 10"))

// Associativity
wl("------ Associativity -------")
uc.Define("Associativity: LeftToRight ~~ Operator: {x} OpX {y} = x / y");
uc.Define("Associativity: RightToLeft ~~ Operator: {x} OpY {y} = x / y");
wl(uc.Eval("3 OpX 4 OpX 5"))
wl(uc.Eval("3 OpY 4 OpY 5"))
```

**Output:**
```
------ Basic examples -------
15
50
12300
------ End user definition -------
987000
------ Boolean format -------
true
false
1
false
TotallyTrue
CompletelyFalse
55
CompletelyFalse
------ Format -------
Answer: <3>
Answer: <String Value --> Hello world!>
Answer: <Additional format: 3>
The Answer: <Additional format: 3>
The Answer: <3>
------ Bootstrap -------
7b
0x7B
7b
------ Overwrite -------
5
50
55
-------
25
2500
2525
------ Lock -------
555
3.14
222
Value cannot be assigned here
222
3.14
-------
105
205
305
205
------ Tokens -------
Undefined identifier
Undefined identifier
9
15
------ Precedence -------
45
90
------ Associativity -------
0.15
3.75
```

---

### Example ID: 8

**Description:** Defining a constant

**Code:**
```pseudocode
uc.DefineVariable("MyVar = 10");
uc.DefineConstant("MyPi = 3.14");

wl(uc.Eval("MyVar"))
wl(uc.Eval("MyPi"))

uc.EvalStr("MyVar = 20"); // Attempt to change MyVar
wl(uc.@Error().@Message())

uc.EvalStr("MyPi = 25"); // Attempt to change MyPi
wl(uc.@Error().@Message())

wl(uc.EvalStr("MyVar"))
wl(uc.EvalStr("MyPi"))
```

**Output:**
```
10
3.14
No error
Value cannot be assigned here
20
3.14
```

---

### Example ID: 10

**Description:** Miscellaneous end-user functions defined with DefineFunction()

**Code:**
```pseudocode
wl("---- Simple function def ----")
uc.DefineFunction("f(x) = x ^ 2 + 5");
wl(uc.Eval("f(10)"))

wl("---- Function overloading ----")
// Overloading based on parameter type or number of parameters
uc.DefineFunction("MyOverload(x As Double) = x + x");
uc.DefineFunction("MyOverload(x As String) As String = x + x");
uc.DefineFunction("MyOverload(x As String, y As String) As String = x + y");
uc.DefineFunction("MyOverload(x, y) = x + y");
wl(uc.EvalStr("MyOverload(5)"))
wl(uc.EvalStr("MyOverload('Ha')"))
wl(uc.EvalStr("MyOverload('Hello ', 'world!')"))
wl(uc.EvalStr("MyOverload(5, 10)"))

wl("---- Definition hiding/un-hiding ----")
// Shadowing (hiding) definitions
uc.DefineFunction("h(x) = x * 10");
wl(uc.Eval("h(3)"))
var hFunc = uc.DefineFunction("h(x) = x * 100"); // hides previous def
wl(uc.Eval("h(3)"))
hFunc.Release(); // Releasing this restores previous def
wl(uc.Eval("h(3)"))

wl("---- Optional parameters ----")
uc.DefineFunction("Opt(x, y = 5, z As String = 'Hello') = x + y + Length(z)");
wl(uc.Eval("Opt(10)"))
wl(uc.Eval("Opt(10, 20)"))
wl(uc.Eval("Opt(10, 20, 'Just a test 123')"))

wl("---- Recursion ----")
uc.DefineFunction("Factorial(x) = iif(x > 1, x * Factorial(x - 1), 1)");
uc.DefineFunction("Fib(n) = IIf(n < 2, n, Fib(n - 1) + Fib(n - 2))");
wl(uc.Eval("Factorial(5)"))
wl(uc.Eval("Fib(10)"))

// Bootstrap - builds new def on top of existing one
wl("------ Bootstrapping -------")
wl(uc.EvalStr("Hex(123)")) // uses "built-in" version of Hex()
[cpp]auto MyHex = uc.DefineFunction("Hex(number As Int) As String = '0x' + UCase(Hex(number))", 0, uCalc::DataType::Empty, true);[/cpp]
[cs]var MyHex = uc.DefineFunction("Hex(number As Int) As String = '0x' + UCase(Hex(number))", bootstrap: true);[/cs]
[vb]Dim MyHex = uc.DefineFunction("Hex(number As Int) As String = '0x' + UCase(Hex(number))", bootstrap:=True);[/vb]
wl(uc.EvalStr("Hex(123)"))
MyHex.Release();
wl(uc.EvalStr("Hex(123)"))

// Overwrite - useful for spreadsheet-like functionality
wl("------ Overwrite -------")
[cpp]uc.DefineFunction("SpreadsheetCell_A1() = 5", 0, uCalc::DataType::Empty, false, true);
uc.DefineFunction("SpreadsheetCell_B2() = SpreadsheetCell_A1() * 10", 0, uCalc::DataType::Empty, false, true);
uc.DefineFunction("SpreadsheetCell_C3() = SpreadsheetCell_A1() + SpreadsheetCell_B2()", 0, uCalc::DataType::Empty, false, true);[/cpp]
[cs]uc.DefineFunction("SpreadsheetCell_A1() = 5", overwrite: true);
uc.DefineFunction("SpreadsheetCell_B2() = SpreadsheetCell_A1() * 10", overwrite: true);
uc.DefineFunction("SpreadsheetCell_C3() = SpreadsheetCell_A1() + SpreadsheetCell_B2()", overwrite: true);[/cs]
[vb]uc.DefineFunction("SpreadsheetCell_A1() = 5", overwrite:=true);
uc.DefineFunction("SpreadsheetCell_B2() = SpreadsheetCell_A1() * 10", Overwrite:=true);
uc.DefineFunction("SpreadsheetCell_C3() = SpreadsheetCell_A1() + SpreadsheetCell_B2()", overwrite:=true);[/vb]
wl(uc.Eval("SpreadsheetCell_A1()"))
wl(uc.Eval("SpreadsheetCell_B2()"))
wl(uc.Eval("SpreadsheetCell_C3()"))
// SpreadsheetCell_C3() will be affected by the definition changes of SpreadsheetCell_A1() and  SpreadsheetCell_B3()
[cpp]uc.DefineFunction("SpreadsheetCell_B2() = SpreadsheetCell_A1() * 100", 0, uCalc::DataType::Empty, false, true);
uc.DefineFunction("SpreadsheetCell_A1() = 25", 0, uCalc::DataType::Empty, false, true);[/cpp]
[cs]uc.DefineFunction("SpreadsheetCell_B2() = SpreadsheetCell_A1() * 100", overwrite: true);
uc.DefineFunction("SpreadsheetCell_A1() = 25", overwrite: true);[/cs]
[vb]uc.DefineFunction("SpreadsheetCell_B2() = SpreadsheetCell_A1() * 100", overwrite:=true);
uc.DefineFunction("SpreadsheetCell_A1() = 25", overwrite:=true);[/vb]
wl("-------")
// Note: Empty parenthesis are optional for functions with no parameters
wl(uc.Eval("SpreadsheetCell_A1"))
wl(uc.Eval("SpreadsheetCell_B2"))
wl(uc.Eval("SpreadsheetCell_C3"))

// See Define() topic for more





```

**Output:**
```
---- Simple function def ----
105
---- Function overloading ----
10
HaHa
Hello world!
15
---- Definition hiding/un-hiding ----
30
300
30
---- Optional parameters ----
20
35
45
---- Recursion ----
120
55
------ Bootstrapping -------
7b
0x7B
7b
------ Overwrite -------
5
50
55
-------
25
2500
2525
```

---

### Example ID: 11

**Description:** How to define a custom function using a native callback.

**Code:**
```pseudocode
[head]
[callback MyArea]
// Retrieve the 1st and 2nd arguments passed to the function
var Length = cb.Arg(1); 
var Width = cb.Arg(2);

// Calculate the area and return the result to the uCalc engine.
// This logic pattern translates seamlessly across languages.
cb.Return(Length * Width); // Same as cb.ReturnDbl
[/callback]
[body]
uc.DefineFunction("Area(x, y)", MyArea);
wl(uc.Eval("Area(3, 4)"))
```

**Output:**
```
12
```

---

### Example ID: 12

**Description:** Defining a callback function with a variable number of arguments

**Code:**
```pseudocode
[head]
[callback MyAverage]
var(double, Total) = 0;
for(int x = 1 to cb.ArgCount())
   Total = Total + cb.Arg(x);
end for
cb.Return(Total / cb.ArgCount());
[/callback]
[body]
uc.DefineFunction("Average(x ...)", MyAverage);
wl(uc.Eval("Average(10, 3, 7, 4)"))
```

**Output:**
```
6
```

---

### Example ID: 13

**Description:** Passing arg ByHandle to retrieve meta data such as arg data type; and AnyType

**Code:**
```pseudocode
[head]
[callback DisplayArgs]
for(int x = 1 to cb.ArgCount())
   wl(cb.ArgItem(x).ValueStr() + "  Type: " + cb.ArgItem(x).@DataType().@Name())
end for
[/callback]
[body]
uc.DefineFunction("DisplayArgs(ByHandle Arg As AnyType ...)", DisplayArgs);
uc.Eval("DisplayArgs(5, 3+2*#i, 'Hello', True, False, Int16(5+4.1))");
```

**Output:**
```
5  Type: double
3+2i  Type: complex
Hello  Type: string
true  Type: bool
false  Type: bool
9  Type: int16
```

---

### Example ID: 14

**Description:** Passing arg ByExpr (delayed lazy eval) and ByHandle

**Code:**
```pseudocode
[head]
[callback MySum]
   var Total = 0.0;
   var Expr = cb.ArgExpr(1);
   var Start = cb.Arg(2);
   var Finish = cb.Arg(3);
   var Variable = cb.ArgItem(4);

   for(double x = Start to Finish)
      Variable.Value(x);
      Total += Expr.Evaluate();
   end for
   cb.Return(Total);
[/callback]
[body]
uc.DefineVariable("x");
uc.DefineFunction("Sum(ByExpr Expr, Start, Finish, ByHandle Var)", MySum);
wl(uc.Eval("Sum(x ^ 2, 1, 10, x)"))

```

**Output:**
```
385
```

---

### Example ID: 15

**Description:** Returning a string (from a callback)

**Code:**
```pseudocode
[head]
[callback TwiceStr]
   cb.ReturnStr(cb.ArgStr(1) + cb.ArgStr(1));
[/callback]
[body]
uc.DefineFunction("Twice(Txt As String) As String", TwiceStr);
wl(uc.EvalStr("Twice('Bye')"))
```

**Output:**
```
ByeBye
```

---

### Example ID: 16

**Description:** How to handle and retrieve various data types (including pointers) within a callback.

**Code:**
```pseudocode
[head]
[callback MyFunction]
   var uc = cb.@uCalc();
   wl("------ MyFunc ------")

   // Retrieve standard 32-bit and 64-bit integer arguments directly
   wl(cb.ArgInt32(1))
   wl(cb.ArgInt64(2))

   // Retrieve the value of a pointer argument by referencing its exact data type.
   wl(uc.ItemOf("Int8").@DataType().ToString(cb.ArgAddr(3)))

   // The Item object correctly identifies the type before conversion
   wl(uc.ItemOf("Int").@DataType().ToString(cb.ArgPtr(4)))
[/callback]

[callback MyFunction2]
   var uc = cb.@uCalc();
   wl("------ MyFunc2 ------")
   wl(uc.DataTypeOf(BuiltInType::Integer_8).ToString(cb.ArgPtr(1)))
[/callback]

[callback MyFunction3]
   var uc = cb.@uCalc();
   wl("------ MyFunc3 ------")
   wl(uc.DataTypeOf(BuiltInType::Integer_16).ToString(cb.ArgPtr(1)))
[/callback]
[body]
uc.DefineVariable("x As Int = 123"); // Int32
uc.DefineVariable("xPtr As Int Ptr = AddressOf(x)");
uc.DefineFunction("MyFunc(a As Int32, b As Int64, c As Byte, d As Int Ptr)", MyFunction);
uc.Eval("MyFunc(x*10, 1+1, 255, xPtr)");

uc.DefineVariable("x2 As Int8 = -123");
uc.DefineVariable("xPtr2 As Int8 Ptr = AddressOf(x2)");
uc.DefineFunction("MyFunc2(d As Int8 Ptr)", MyFunction2);
uc.Eval("MyFunc2(xPtr2)");

uc.DefineVariable("x3 As Int16 = 1234");
uc.DefineVariable("xPtr3 As Int16 Ptr = AddressOf(x3)");
uc.DefineFunction("MyFunc3(d As Int16 Ptr)", MyFunction3);
uc.Eval("MyFunc3(xPtr3)");
```

**Output:**
```
------ MyFunc ------
1230
2
-1
123
------ MyFunc2 ------
-123
------ MyFunc3 ------
1234
```

---

### Example ID: 17

**Description:** DefineVariable examples

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var MyInt = uc.DefineVariable("MyInt As Int");
var MyStr = uc.DefineVariable("MyStr As String");
uc.DefineVariable("OtherStr = 'string type inferred'");
uc.DefineVariable("MyInt16 = Int16(100/3)"); // type inferred
uc.DefineVariable("MyBool = True"); // type inferred
uc.DefineVariable("MyComplex = 3 + 4*#i"); // type inferred

MyVar.Value(123);
MyInt.ValueInt32(456);
MyStr.ValueStr("This is a test");

wl("MyVar = " + uc.EvalStr("MyVar"))
wl("MyInt = " + uc.EvalStr("MyInt"))
wl("MyStr = " + uc.EvalStr("MyStr"))
wl("OtherStr = " + uc.EvalStr("OtherStr"))
wl("MyInt16 = " + uc.EvalStr("MyInt16"))
wl("MyBool = " + uc.EvalStr("MyBool"))
wl("MyComplex = " + uc.EvalStr("MyComplex"))
wl("---")
wl(MyVar.Value())
wl(MyInt.ValueInt32())
wl(MyStr.ValueStr())
wl("---")
wl(uc.ItemOf("MyVar").@DataType().@Name())
wl(uc.ItemOf("MyInt").@DataType().@Name())
wl(uc.ItemOf("MyStr").@DataType().@Name())
wl(uc.ItemOf("OtherStr").@DataType().@Name())
wl(uc.ItemOf("MyInt16").@DataType().@Name())
wl(uc.ItemOf("MyBool").@DataType().@Name())
wl("---")

var Expression = "x^2 * 10";
var VarX = uc.DefineVariable("x");
var ParsedExpr = uc.Parse(Expression);

w("Expression = ")
wl(Expression)
for (int x = 1 to 10)
   VarX.Value(x); // In C++ you can skip this by passing &x to DefineVariable
   wl("x = " + VarX.ValueStr() + "  Result = " + ParsedExpr.EvaluateStr())
end for

ParsedExpr.Release();
VarX.Release();
```

**Output:**
```
MyVar = 123
MyInt = 456
MyStr = This is a test
OtherStr = string type inferred
MyInt16 = 33
MyBool = true
MyComplex = 3+4i
---
123
456
This is a test
---
double
int
string
string
int16
bool
---
Expression = x^2 * 10
x = 1  Result = 10
x = 2  Result = 40
x = 3  Result = 90
x = 4  Result = 160
x = 5  Result = 250
x = 6  Result = 360
x = 7  Result = 490
x = 8  Result = 640
x = 9  Result = 810
x = 10  Result = 1000
```

---

### Example ID: 18

**Description:** DefineVariable; using pointers

**Code:**
```pseudocode
var Int8Var = uc.DefineVariable("x As Int8 = -1");
var Int16Var = uc.DefineVariable("y As Int16 = -1");
var StrVar = uc.DefineVariable("MyStr = 'Hello there'");
wl(uc.EvalStr("x"))
wl(uc.EvalStr("y"))
wl(uc.EvalStr("MyStr"))

var xPtr = uc.DefineVariable("xPtr As Pointer"); // General pointer
var yPtr = uc.DefineVariable("yPtr As Int16u Ptr"); // pointer specific to unsigned Int16
var yPtrB = uc.DefineVariable("yPtrB As Int16 Ptr = AddressOf(y)"); // Using AddressOf
var StrPtr = uc.DefineVariable("StrPtr As String Ptr");
xPtr.ValuePtr(Int8Var.ValueAddr()); // Sets the pointer address
yPtr.ValuePtr(Int16Var.ValueAddr()); // Note: address of signed Int16 going to an unsigned Ptr
StrPtr.ValuePtr(StrVar.ValueAddr());

// Note: for the ints we are now returning unsigned values; so -1 turns into positive numbers
wl(uc.EvalStr("ValueAt(Int8u, xPtr)")) // Type required because it's defined as generar pointer
wl(uc.EvalStr("ValueAt(yPtr)")) // Type name not needed because it's defined as Int16u Ptr
wl(uc.EvalStr("ValueAt(yPtrB)"))
wl(uc.EvalStr("ValueAt(StrPtr)"))

// Iterate through uc.ItemOf(ItemIs.DataType, n).Name()
// to see data type names you can use with ValueAt

var OtherInt = uc.DefineVariable("OtherInt As Int16 = 1234");
uc.DataTypeOf(BuiltInType::Integer_16).SetScalar(Int16Var.ValueAddr(), OtherInt.ValueAddr());

wl(uc.EvalStr("OtherInt"))
wl(uc.EvalStr("ValueAt(yPtrB)"))





```

**Output:**
```
-1
-1
Hello there
255
65535
-1
Hello there
1234
1234
```

---

### Example ID: 19

**Description:** Setting a variable value

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var ByteVar = uc.DefineVariable("ByteVar As Int8");
var Int16uVar = uc.DefineVariable("Int16uVar As Int16u");
var Int32uVar = uc.DefineVariable("Int32uVar As Int32u");
var Int64uVar = uc.DefineVariable("Int64uVar As Int64u");
var SingleVar = uc.DefineVariable("SingleVar As Single");
var DoubleVar = uc.DefineVariable("DoubleVar As Double");
var StringVar = uc.DefineVariable("StringVar As String");

MyVar.Value(1.25);
ByteVar.ValueByte(255);
Int16uVar.ValueInt16(-1);
Int32uVar.ValueInt32(-1);
Int64uVar.ValueInt64(-1);
SingleVar.ValueSng([C](float)[/C]1.5);
DoubleVar.ValueDbl(2.5);
StringVar.ValueStr("Test");

wl(MyVar.Value())
wl([C](int)[/C]ByteVar.ValueByte())
wl(Int16uVar.ValueInt16())
wl(Int32uVar.ValueInt32())
wl(Int64uVar.ValueInt64())
wl(SingleVar.ValueSng())
wl(DoubleVar.ValueDbl())
wl(StringVar.ValueStr())
wl("---")
wl("MyVar value: " + uc.EvalStr("MyVar"))
wl("ByteVar value: " + uc.EvalStr("ByteVar"))
wl("Int16uVar value: " + uc.EvalStr("Int16uVar"))
wl("Int32uVar value: " + uc.EvalStr("Int32uVar"))
wl("Int64uVar value: " + uc.EvalStr("Int64uVar"))
wl("SingleVar value: " + uc.EvalStr("SingleVar"))
wl("DoubleVar value: " + uc.EvalStr("DoubleVar"))
wl("StringVar value: " + uc.EvalStr("StringVar"))
```

**Output:**
```
1.25
255
-1
-1
-1
1.5
2.5
Test
---
MyVar value: 1.25
ByteVar value: -1
Int16uVar value: 65535
Int32uVar value: 4294967295
Int64uVar value: 18446744073709551615
SingleVar value: 1.5
DoubleVar value: 2.5
StringVar value: Test
```

---

### Example ID: 21

**Description:** Evaluating expressions

**Code:**
```pseudocode
// See EvalStr for more examples.

wl(uc.Eval("1+1"))
wl(uc.Eval("5*(3+9)^2"))
wl(uc.Eval("Length('This is a test')"))
```

**Output:**
```
2
720
14
```

---

### Example ID: 22

**Description:** How to perform a summation in a loop efficiently using Execute() instead of Evaluate().

**Code:**
```pseudocode
var VariableX = uc.DefineVariable("x = 0");
var Total = uc.DefineVariable("Total");
var(string, Expression) = "x++; Total = Total + x^2 + 5";

var ParsedExpr = uc.Parse(Expression);

for(double x = 1 to 10)
   // Execute() runs the parsed expression without the overhead of returning a value.
   // This provides near-native performance for loops across C#, VB, and C++.
   ParsedExpr.Execute();

   // Evaluate string interpolation to output the final calculated total
   wl(uc.EvalStr("$'{x}   Sub total = {Total}'"))
end for

wl(uc.EvalStr("$'Total = {Total}'"))

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
1   Sub total = 6
2   Sub total = 15
3   Sub total = 29
4   Sub total = 50
5   Sub total = 80
6   Sub total = 121
7   Sub total = 175
8   Sub total = 244
9   Sub total = 330
10   Sub total = 435
Total = 435
```

---

### Example ID: 23

**Description:** Evaluating expressions returned as string

**Code:**
```pseudocode
uc.DefineVariable("x = 123");
uc.DefineVariable("y");

wl(uc.EvalStr("1 + 1"))
wl(uc.EvalStr("UCase('Hello ' + 'world!')"))
wl(uc.EvalStr("$'Interpolation: {2+3}'"))
wl(uc.EvalStr("#b101 + #hAE"))
wl(uc.EvalStr("Hex(1234)"))
wl(uc.EvalStr("(3+5*#i)^2"))
wl(uc.EvalStr("3 > 4"))
wl(uc.EvalStr("Max(5, 10, 3, -5)"))
wl(uc.EvalStr("x * 10"))
uc.EvalStr("x = 456");
wl(uc.EvalStr("x"))
wl(uc.EvalStr("2+4, 5+4, 10+20"))
wl(uc.EvalStr("y=100; ForLoop(x, 1, 10, 1, y = y + x); y"))
wl(uc.EvalStr("10 / "))
```

**Output:**
```
2
HELLO WORLD!
Interpolation: 5
179
4d2
-16+30i
false
10
1230
456
30
155
Syntax error
```

---

### Example ID: 24

**Description:** Finding the precedence level of an operator

**Code:**
```pseudocode
uc.DefineOperator("{a As Bool} ## {b As Bool} As Bool = a And b", uc.ItemOf("And").@Precedence());
wl(uc.EvalStr("true Or false ## 2 > 5"))

uc.ItemOf("##").SetPrecedence(uc.ItemOf("Or").@Precedence());
wl(uc.EvalStr("true Or false ## 2 > 5"))
```

**Output:**
```
true
false
```

---

### Example ID: 25

**Description:** Setting variables of any data type

**Code:**
```pseudocode
var Int32Var = uc.DefineVariable("Int32Var As Int32");
var ByteVar = uc.DefineVariable("ByteVar As Byte");
var StrVar = uc.DefineVariable("StrVar As String");
var SngVar = uc.DefineVariable("SngVar As Single");

Int32Var.Value("4.25"); // Will be converted to integer
ByteVar.Value("-1");    // Will be converted to unsigned byte
StrVar.Value("'Test'");
SngVar.Value("1 + 0.25");

wl(uc.Eval("Int32Var"))
wl(uc.Eval("ByteVar"))
wl(uc.EvalStr("StrVar"))
wl(uc.EvalStr("SngVar"))

```

**Output:**
```
4
255
Test
1.25
```

---

### Example ID: 26

**Description:** Format using callback functions

**Code:**
```pseudocode
[head]
[callback OutputAnswerCB]
  cb.ReturnStr("Answer: " + cb.ArgStr(1));
[/callback]
[callback OutputSymbolCB]
  cb.ReturnStr("==> " + cb.ArgStr(1));
[/callback]
[callback OutputBoolCB]
  if (cb.ArgStr(1) == "false")
    cb.ReturnStr("No");
  else if (cb.ArgStr(1) == "true")
    cb.ReturnStr("Yes");
  end if
[/callback]
[body]

// This format inserts "Answer: " in front of every result
var OutputAnswer = uc.Format([VB]AddressOf[/VB] OutputAnswerCB);
wl(uc.EvalStr("10+20"))
wl(uc.EvalStr("'Hello '+'world'"))
wl(uc.EvalStr("5 > 10"))
wl("---")

// This one inserts ==> in front of the result
// The previously defined "Answer: " output is still prepended as well
var OutputSymbol = uc.Format([VB]AddressOf[/VB] OutputSymbolCB);
wl(uc.EvalStr("10+20"))
wl(uc.EvalStr("'Hello '+'world'"))
wl(uc.EvalStr("5 > 10"))
wl("---")

// Causes Boolean values to return Yes or No (instead of true or false)
var OutputBool = uc.Format([VB]AddressOf[/VB] OutputBoolCB, "Bool");
wl(uc.EvalStr("10+20"))
wl(uc.EvalStr("'Hello '+'world'"))
wl(uc.EvalStr("5 > 10"))
wl(uc.EvalStr("5 < 10"))
wl("---")

// The previously defined "==>" output is removed
OutputSymbol.Release();
wl(uc.EvalStr("10+20"))
wl(uc.EvalStr("'Hello '+'world'"))
wl(uc.EvalStr("5 > 10"))
wl(uc.EvalStr("5 < 10"))
```

**Output:**
```
Answer: 30
Answer: Hello world
Answer: false
---
Answer: ==> 30
Answer: ==> Hello world
Answer: ==> false
---
Answer: ==> 30
Answer: ==> Hello world
Answer: ==> No
Answer: ==> Yes
---
Answer: 30
Answer: Hello world
Answer: No
Answer: Yes
```

---

### Example ID: 27

**Description:** Output formatting without using a callback

**Code:**
```pseudocode
// The output is surrounded by < and >, and prepended with Answer:
uc.Format("Result = 'Answer: <' + Result + '>'");

wl(uc.EvalStr("10+20"))
wl(uc.EvalStr("'Hello '+'world'"))
wl(uc.EvalStr("5 > 10"))

uc.FormatRemove();
```

**Output:**
```
Answer: <30>
Answer: <Hello world>
Answer: <false>
```

---

### Example ID: 28

**Description:** Different output formats for different data types

**Code:**
```pseudocode
// String results will be surrounded by << and >>, while Boolean will be surrounded by [[ and ]]
uc.Format("DataType: String, Def: val = '<<' + val + '>>' ");
uc.Format("Bool, val = '[[' + val + ']]'"); // Shortcut notation without "DataType" or "Def"

wl(uc.EvalStr("10+20"))
wl(uc.EvalStr("'Hello '+'world'"))
wl(uc.EvalStr("5 > 10"))
wl(uc.EvalStr("5 < 10"))

uc.FormatRemove();
wl("---")
wl(uc.EvalStr("10+20"))
wl(uc.EvalStr("'Hello '+'world'"))
wl(uc.EvalStr("5 > 10"))
wl(uc.EvalStr("5 < 10"))
```

**Output:**
```
30
<<Hello world>>
[[false]]
[[true]]
---
30
Hello world
false
true
```

---

### Example ID: 29

**Description:** Inserts formatting in specified sequence

**Code:**
```pseudocode
uc.Format("Result = 'Answer: ' + Result");
uc.Format("DataType: String, Def: val = '<<' + val + '>>' ");
uc.Format("DataType: Bool, Def: val = '[[' + val + ']]'");

// Note the difference between where "Bool: " and "String: " are displayed in the result
uc.Format("InsertAt: 0, DataType: Bool, Def: val = 'Bool: ' + val");  // Inserts at 0th position of Bool
uc.Format("InsertAt: 1, DataType: String, Def: val = 'String: ' + val"); // Inserts at 1st position of String
wl(uc.EvalStr("10+20"))
wl(uc.EvalStr("'Hello '+'world'"))
wl(uc.EvalStr("5 > 10"))
wl("---")

// This fomratting will be the last one to take effect
uc.Format("InsertAt: 0, Def: val = 'Outer: ' + val");
wl(uc.EvalStr("10+20"))
wl(uc.EvalStr("'Hello '+'world'"))
wl(uc.EvalStr("5 > 10"))
wl("---")

// This formatting will be the first one to take effect
uc.Format("val = 'Inner: ' + val"); // Optionally InsertAt: -1 could have been used
wl(uc.EvalStr("10+20"))
wl(uc.EvalStr("'Hello '+'world'"))
wl(uc.EvalStr("5 > 10"))
wl("---")

uc.FormatRemove();

wl(uc.EvalStr("10+20"))
wl(uc.EvalStr("'Hello '+'world'"))
wl(uc.EvalStr("5 > 10"))
```

**Output:**
```
Answer: 30
Answer: String: <<Hello world>>
Bool: Answer: [[false]]
---
Outer: Answer: 30
Outer: Answer: String: <<Hello world>>
Outer: Bool: Answer: [[false]]
---
Outer: Answer: Inner: 30
Outer: Answer: String: <<Inner: Hello world>>
Outer: Bool: Answer: [[Inner: false]]
---
30
Hello world
false
```

---

### Example ID: 31

**Description:** Illustrates the core relationship between the uCalc engine, an Item (variable), and a compiled Expression.

**Code:**
```pseudocode
var VariableX = uc.DefineVariable("x");
var Expression = "x^2 * 10"; // Replace this with your expression

wl("--- Efficient: Parse() once, then Evaluate() in a loop ---")
var ParsedExpr = uc.Parse(Expression);
for(double x = 1 to 10)
   VariableX.Value(x);
   wl(ParsedExpr.Evaluate())
end for

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
--- Efficient: Parse() once, then Evaluate() in a loop ---
10
40
90
160
250
360
490
640
810
1000
```

---

### Example ID: 32

**Description:** Displaying Integer (Int32) results with Evaluate32

**Code:**
```pseudocode
var VariableX = uc.DefineVariable("x");

var ParsedExpr = uc.Parse("x / 2", "Integer"); // Causes output of "x / 2" to convert to an integer

// NOTE: EvaluateInt32 should only be used when Parse() explicitly specifies Integer
// (Or Int, or Int32) as the second argument, or if the expression evaluates to an integer
// (such as evaluating a variable that was explicitly defined as integer;
// other arithmetic operators typically evaluate to Double floating point).

for (double x = 1 to 10)
   VariableX.Value(x);
   wl("x = " + VariableX.ValueStr() + "  Result = " + to_string(ParsedExpr.EvaluateInt32()))
end for

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
x = 1  Result = 0
x = 2  Result = 1
x = 3  Result = 1
x = 4  Result = 2
x = 5  Result = 2
x = 6  Result = 3
x = 7  Result = 3
x = 8  Result = 4
x = 9  Result = 4
x = 10  Result = 5
```

---

### Example ID: 33

**Description:** Doing an Eval in the same uCalc instance a variable belongs to

**Code:**
```pseudocode
New(uCalc, uc1)
New(uCalc, uc2)

var x1 = uc1.DefineVariable("x = 5");
var x2 = uc2.DefineVariable("x = 6");

wl(x1.@uCalc().Eval("x*10")) // Same as uc1.Eval("x*10")
wl(x2.@uCalc().Eval("x*10")) // Same as uc2.Eval("x*10")

uc1.Release();  // Since x1 is part of uc1, x1 is automatically released as well
uc2.Release();  // Since x2 is part of uc2, x2 is automatically released as well

// You should no longer use x1 or x2 because they were part of uc1 & uc2
// Don not try x1.uCalc().Eval("x*10"); or x2.uCalc().Eval("x*10");
```

**Output:**
```
50
60
```

---

### Example ID: 37

**Description:** Raising an error in a callback with ErrorRaise

**Code:**
```pseudocode
[head]
[callback RaiseErrorCallback]
if (cb.Arg(1) == 123)
  cb.@Error().Raise(ErrorCode::Unrecognized_Command);
end if
cb.Return(cb.Arg(1));
[/callback]
[body]

uc.DefineFunction("ErrRaiseTest(Value)", RaiseErrorCallback);
wl(uc.EvalStr("ErrRaiseTest(111)"))
wl(uc.EvalStr("ErrRaiseTest(123)")) // The callback arbitrarily raises an error for 123
```

**Output:**
```
111
Unrecognized command
```

---

### Example ID: 39

**Description:** Raises an error in a callback using a customized message with ErrorRaiseMessage

**Code:**
```pseudocode
[head]
[callback RaiseErrorMessageCallback]
if (cb.Arg(1) == 123)
   cb.@Error().Raise("I do not like this value!");
   cb.Return(cb.Arg(1));
end if
[/callback]
[body]

uc.DefineFunction("ErrRaiseMsgTest(Value)", RaiseErrorMessageCallback);
wl(uc.EvalStr("ErrRaiseMsgTest(111)"))
wl(uc.EvalStr("ErrRaiseMsgTest(123)"))
```

**Output:**
```
111
I do not like this value!
```

---

### Example ID: 40

**Description:** Determining properties of an expression part

**Code:**
```pseudocode
[head]
[callback ItemCallback]
   wl("Name: ", cb.@Item().@Name())
   wl("Data type: ", cb.@Item().@DataType().@Name())
   wl("Param count: ", cb.@Item().@Count())
   w("Procedure type: ")
   if (cb.@Item().IsProperty(ItemIs::Operator))
      wl("Operator")
   else if (cb.@Item().IsProperty(ItemIs::Function))
      wl("Function")
   end if
   wl(cb.@Item().@Text())
   wl(cb.@Item().@Description())
   wl("---")
[/callback]
[body]

uc.DefineFunction("AAA() As Double", ItemCallback).@Description("Does this and that");
uc.DefineFunction("BBB(x, y, z) As String", ItemCallback).@Description("Does something else");
uc.DefineOperator("{x} CCC {y} As Int32", 0, Associativity::LeftToRight, ItemCallback);

uc.EvalStr("AAA()");
uc.EvalStr("BBB(9, 8, 7)");
uc.EvalStr("5 CCC 4");

```

**Output:**
```
Name: aaa
Data type: double
Param count: 0
Procedure type: Function
Function: AAA() As Double
Does this and that
---
Name: bbb
Data type: string
Param count: 3
Procedure type: Function
Function: BBB(x, y, z) As String
Does something else
---
Name: ccc
Data type: int
Param count: 2
Procedure type: Operator
Operator: {x} CCC {y} As Int32

---
```

---

### Example ID: 41

**Description:** Displaying the data type of a parsed expression

**Code:**
```pseudocode
wl(uc.Parse(" 3 + 6 * 10 ").@DataType().@Name())
wl(uc.Parse(" 'This ' + 'is a string' ").@DataType().@Name())
wl(uc.Parse(" 2 + 8 * #i / 2").@DataType().@Name())
wl(uc.Parse(" 10 + 2 > 3").@DataType().@Name())
```

**Output:**
```
double
string
complex
bool
```

---

### Example ID: 42

**Description:** Displaying strings with EvaluateStr()

**Code:**
```pseudocode
var VariableX = uc.DefineVariable("x As Int32");
var MyStringVar = uc.DefineVariable("MyString = 'Hello world'");
var ParsedExpr = uc.Parse("SubStr(MyString, x, 1)");
var StrLength = uc.Eval("Length(MyString)");

for (int x = 0 to uc.Eval("Length(MyString) - 1"))
   VariableX.ValueInt32(x);
   w(ParsedExpr.EvaluateStr() + ".")
end for
```

**Output:**
```
H.e.l.l.o. .w.o.r.l.d.
```

---

### Example ID: 43

**Description:** Displaying complex number outputs with EvaluateStr()

**Code:**
```pseudocode
var VariableX = uc.DefineVariable("x");
var ParsedExpr = uc.Parse("x * #i + 5", "Complex");

for (double x = 1 to 10)
   VariableX.Value(x);
   // Note: EvaluateStr works with any data type;
   wl(uc.EvalStr("$'x = {x}  Result = '") + ParsedExpr.EvaluateStr())   
end for

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
x = 1  Result = 5+1i
x = 2  Result = 5+2i
x = 3  Result = 5+3i
x = 4  Result = 5+4i
x = 5  Result = 5+5i
x = 6  Result = 5+6i
x = 7  Result = 5+7i
x = 8  Result = 5+8i
x = 9  Result = 5+9i
x = 10  Result = 5+10i
```

---

### Example ID: 44

**Description:** Displaying an expression of unsigned byte as a signed byte by using a Pointer

**Code:**
```pseudocode
var VariableX = uc.DefineVariable("x As Int");
var ParsedExpr = uc.Parse("x + 125", "Int8u");

for (int x = 1 to 10)
   VariableX.ValueInt32(x);
   wl("x = ", x, "  Int8 result = ", uc.ValueAt(ParsedExpr.EvaluateVoid(), "Int8"))
end for

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
x = 1  Int8 result = 126
x = 2  Int8 result = 127
x = 3  Int8 result = -128
x = 4  Int8 result = -127
x = 5  Int8 result = -126
x = 6  Int8 result = -125
x = 7  Int8 result = -124
x = 8  Int8 result = -123
x = 9  Int8 result = -122
x = 10  Int8 result = -121
```

---

### Example ID: 45

**Description:** ItemOf selection between infix version of - (minus) operator and unary prefix version with Properties

**Code:**
```pseudocode

// Returns number of operands for the given operators
wl(uc.ItemOf("-", uCalc::Properties(ItemIs::Infix)).@Count())
wl(uc.ItemOf("-", uCalc::Properties(ItemIs::Prefix)).@Count())

[C]// You can pass one property directly in C++ and C#, but not VB
wl(uc.ItemOf("-", ItemIs::Infix).@Count())
wl(uc.ItemOf("-", ItemIs::Prefix).@Count())[/C]
[VB]
// You can pass one property directly in C++ and C#, but not VB
wl(2) // C++ and C# only: uc.ItemOf("-", ItemIs::Infix).@Count();
wl(1) // C++ and C# only: uc.ItemOf("-", ItemIs::Prefix).@Count();[/VB]
```

**Output:**
```
2
1
2
1
```

---

### Example ID: 46

**Description:** Dispaying the number of elements in an array

**Code:**
```pseudocode
[head]
[callback MyAverage]
var(double, Total) = 0;
for(int x = 1 to cb.ArgCount())
   Total = Total + cb.Arg(x);
end for
cb.Return(Total / cb.ArgCount());
[/callback]
[body]
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");

wl("Elements in MyArrayA: ", MyArrayA.@Count())
wl("Elements in MyArrayB: ", MyArrayB.@Count())
wl("Params in FuncA(): ", FunctionA.@Count())
wl("Params in FuncB(): ", FunctionB.@Count())
wl("Params in FuncC(): ", FunctionC.@Count()) // -1 or 2^n-1 (n=32 or 64)
wl("Params in FuncD(): ", FunctionD.@Count())
wl("Operands in ! operator: ", uc.ItemOf("!").@Count())
wl("Operands in > operator: ", uc.ItemOf(">").@Count())
```

**Output:**
```
Elements in MyArrayA: 5
Elements in MyArrayB: 15
Params in FuncA(): 3
Params in FuncB(): 4
Params in FuncC(): -1
Params in FuncD(): 0
Operands in ! operator: 1
Operands in > operator: 2
```

---

### Example ID: 47

**Description:** Determining whether items are functions, or arrays, etc.

**Code:**
```pseudocode
uc.DefineVariable("MyVar");

wl(uc.EvalStr("'Cos is a function? '"), bool(uc.ItemOf("Cos").IsProperty(ItemIs::Function)))
wl(uc.EvalStr("'Cos is a variable? '"), bool(uc.ItemOf("Cos").IsProperty(ItemIs::Variable)))
wl(uc.EvalStr("'Cos is an operator? '"), bool(uc.ItemOf("Cos").IsProperty(ItemIs::Operator)))
wl(uc.EvalStr("'MyVar is a function? '"), bool(uc.ItemOf("MyVar").IsProperty(ItemIs::Function)))
wl(uc.EvalStr("'MyVar is a variable? '"), bool(uc.ItemOf("MyVar").IsProperty(ItemIs::Variable)))
wl(uc.EvalStr("'MyVar is an operator? '"), bool(uc.ItemOf("MyVar").IsProperty(ItemIs::Operator)))
wl(uc.EvalStr("'+ is a function? '"), bool(uc.ItemOf("+").IsProperty(ItemIs::Function)))
wl(uc.EvalStr("'+ is a variable? '"), bool(uc.ItemOf("+").IsProperty(ItemIs::Variable)))
wl(uc.EvalStr("'+ is an operator? '"), bool(uc.ItemOf("+").IsProperty(ItemIs::Operator)))
wl(uc.EvalStr("'Cos not found? '"), bool(uc.ItemOf("Cos").IsProperty(ItemIs::NotFound)))
wl(uc.EvalStr("'XYZABC not found? '"), bool(uc.ItemOf("XYZABC").IsProperty(ItemIs::NotFound)))
```

**Output:**
```
Cos is a function? True
Cos is a variable? False
Cos is an operator? False
MyVar is a function? False
MyVar is a variable? True
MyVar is an operator? False
+ is a function? False
+ is a variable? False
+ is an operator? True
Cos not found? False
XYZABC not found? True
```

---

### Example ID: 48

**Description:** Renames the Cos function (which is in Radian) to CosR and defines Cos in Degrees

**Code:**
```pseudocode
uc.DefineConstant("pi = Atan(1) * 4");

// Original Cosine behavior with Radian
wl(uc.EvalStr("Cos(pi)"))
wl(uc.EvalStr("Cos(180)"))

// Cos is renamed to CosR so that Cos can now be defined in Degree
uc.ItemOf("Cos").Rename("CosR");
uc.DefineFunction("Cos(x) = CosR(x*pi/180)");

// Now Cos is in Degree
wl(uc.EvalStr("Cos(pi)"))
wl(uc.EvalStr("Cos(180)"))

// This is the original function now named CosR
wl(uc.EvalStr("CosR(pi)"))
wl(uc.EvalStr("CosR(180)"))
// Note: Some functions may be overloaded, such as the Cos function in
// this example, which has a definition for Double and another for Complex.
// This example renames only the Double precision version.
// You can use NextOverload() and DataType() to pinpoint the one you want
```

**Output:**
```
-1
-0.59846006905785
0.99849714986386
-1
-1
-0.59846006905785
```

---

### Example ID: 49

**Description:** Setting a variable value by pointer

**Code:**
```pseudocode
var x = uc.DefineVariable("x = 123");
var y = uc.DefineVariable("y");

y.ValueByPtr(x.ValueAddr());

wl(uc.Eval("x"))
wl(uc.Eval("y"))
```

**Output:**
```
123
123
```

---

### Example ID: 50

**Description:** Displaying the data type name and size of a variable

**Code:**
```pseudocode
var MyVariable = uc.DefineVariable("MyVariable");
wl("MyVariable type: " + MyVariable.@DataType().@Name())
wl("MyVariable size: ", MyVariable.@DataType().@ByteSize())
```

**Output:**
```
MyVariable type: double
MyVariable size: 8
```

---

### Example ID: 51

**Description:** Returning data type names for the different definitions of the "+" operator

**Code:**
```pseudocode
var PlusOperator = uc.ItemOf("+");

while (PlusOperator.NotEmpty())
   wl("Def: " + PlusOperator.@Text() + "  Type: " + PlusOperator.@DataType().@Name())
   PlusOperator = PlusOperator.NextOverload();
end while
```

**Output:**
```
Def: Operator: 70 +{x}  Type: double
Def: Operator: 50 {x} + {y}  Type: double
Def: Operator: 50 {x As Int} + {y As Int} As Int  Type: int
Def: Operator: 50 {x As String} + {y As String} As String  Type: string
Def: Operator: 50 {x As Complex} + {y As Complex} As Complex  Type: complex
Def: Operator: 50 {ByHandle x As AnyType Ptr} + {y As Int} As SameTypeAs:0 Ptr  Type: sametypeas:ptr
Def: Operator: 50 {ByHandle x As AnyType} + {ByHandle y As String} As String  Type: string
Def: Operator: 50 {ByHandle x As String} + {ByHandle y As AnyType} As String  Type: string
```

---

### Example ID: 52

**Description:** Inspecting the parts of a syntax construct

**Code:**
```pseudocode
uc.DefineFunction("MyFunction(x) = x * 2");
wl(uc.ItemOf("MyFunction").@Text())
```

**Output:**
```
Function: MyFunction(x) = x * 2
```

---

### Example ID: 54

**Description:** Error handler to auto-define variables

**Code:**
```pseudocode
[head]
// This error handler allows you to use variables that were not
// explicitly defined previously, by defining the unrecognized identifiers
// as variables instead of returning an error
[callback:u AutoVariableDef]
   if (uc.@Error().@Code() == ErrorCode::Undefined_Identifier)
      uc.DefineVariable(uc.@Error().@Symbol());
      uc.@Error().@Response(ErrorHandlerResponse::Resume);
   end if
[/callback]

[body]
uc.@Error().AddHandler(AutoVariableDef);
wl(uc.Eval("AutoTest = 123"))
wl(uc.Eval("AutoTest * 1000"))
```

**Output:**
```
123
123000
```

---

### Example ID: 55

**Description:** Error handler order

**Code:**
```pseudocode
[head]
[callback:u ErrorHandlerA]
wl("Handler A called")
[/callback]

[callback:u ErrorHandlerB]
wl("Handler B called")
[/callback]

[callback:u ErrorHandlerC]
wl("Handler C called")
[/callback]

[callback:u ErrorHandlerD]
wl("Handler D called")
[/callback]

[callback:u ErrorHandlerE]
wl("Handler E called")
[/callback]

[body]
uc.@Error().AddHandler(ErrorHandlerA);
uc.@Error().AddHandler(ErrorHandlerB);
uc.@Error().AddHandler(ErrorHandlerC);
uc.@Error().AddHandler(ErrorHandlerD, -1);
uc.@Error().AddHandler(ErrorHandlerE, 3);

wl(uc.EvalStr("10 / "))
```

**Output:**
```
Handler C called
Handler B called
Handler A called
Handler E called
Handler D called
Syntax error
```

---

### Example ID: 56

**Description:** Alias using symbol object

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar = 123");
var MyAlias = uc.CreateAlias("MyAlias", MyVar);

wl(uc.Eval("MyAlias")) // Contains same value as MyVar
uc.Eval("MyAlias = 456"); // Same as changing MyVar
wl(uc.EvalStr("MyVar")) // MyVar reflects change made in MyAlias
wl("")


// This section below shows how you can have Alias distinguish
// between different variables with the same name

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

// MyVar defined below is a new variable sharing the same name
// MyFunc() will still use the value of the original MyVar
var MyVarAlt = uc.DefineVariable("MyVar = 100");

// The function below uses the new MyVar variable
uc.DefineFunction("MyFunc2() = MyVar + 1");

wl(uc.Eval("MyFunc()"))
wl(uc.Eval("MyFunc2()"))
wl("")

uc.CreateAlias("MyAliasAlt", MyVarAlt);
uc.Eval("MyAlias = 200"); // Changes MyVar used in MyFunc()
uc.Eval("MyAliasAlt = 300"); // Changes MyVar used in MyFunc2()

wl(uc.Eval("MyFunc()"))
wl(uc.Eval("MyFunc2()"))
```

**Output:**
```
123
456

457
101

201
301
```

---

### Example ID: 57

**Description:** Simple alias

**Code:**
```pseudocode
uc.DefineVariable("x = 10");

// Create alias: y behaves exactly like x
uc.CreateAlias("y", "x");

wl(uc.Eval("y + 5"))
```

**Output:**
```
15
```

---

### Example ID: 58

**Description:** Creating alternative names for Define commands

**Code:**
```pseudocode
uc.CreateAlias("VariableDefinition", "Variable", true);
uc.CreateAlias("Method", "Function", true);

uc.Define("VariableDefinition: MyVar = 123");
uc.Define("Method: MyFunc(x) = x * 10");

wl(uc.Eval("MyVar"))
wl(uc.Eval("MyFunc(5)"))
```

**Output:**
```
123
50
```

---

### Example ID: 59

**Description:** Creating a clone of a uCalc object

**Code:**
```pseudocode

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

var Cloned_uc = uc.Clone();

wl(uc.EvalStr("MyVar"))
wl(uc.EvalStr("MyFunc(10)"))

wl(Cloned_uc.EvalStr("MyVar"))
wl(Cloned_uc.EvalStr("MyFunc(10)"))

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

wl(uc.EvalStr("MyVar"))
wl(uc.EvalStr("OtherFunc(5)"))

wl(Cloned_uc.EvalStr("MyVar"))
wl(Cloned_uc.EvalStr("OtherFunc(5)"))
```

**Output:**
```
100
11
100
11
100
Undefined identifier
200
50
```

---

### Example ID: 60

**Description:** Using the default uCalc.GetDefaultInstance() instance

**Code:**
```pseudocode
uCalc::@DefaultInstance().DefineVariable("instance = 'original default'");

New(uCalc, ucB)
New(uCalc, ucC)
New(uCalc, ucD)

ucB.Eval("instance = 'B derived from -> ' + instance");
ucC.Eval("instance = 'C derived from -> ' + instance");
ucD.Eval("instance = 'D derived from -> ' + instance");

ucC.@IsDefault(true);

New(uCalc, ucE)
ucE.Eval("instance = 'E derived from -> ' + instance");

wl(uCalc::@DefaultInstance().EvalStr("'Default: ' + instance"))

wl(uc.EvalStr("instance")) // Note: this is not, nor was the default
wl(ucB.EvalStr("instance"))
wl(ucC.EvalStr("instance"))
wl(ucD.EvalStr("instance"))
wl(ucE.EvalStr("instance"))

// Note: Unlike this example, it is generally best to always
// create a new instance first and then set it as default
```

**Output:**
```
Default: C derived from -> original default
Undefined identifier
B derived from -> original default
C derived from -> original default
D derived from -> original default
E derived from -> C derived from -> original default
```

---

### Example ID: 61

**Description:** Setting default uCalc instance with uCalc.IsDefault(); also clearing all uCalc instances from default list

**Code:**
```pseudocode
uCalc::@DefaultInstance().DefineVariable("val = 'original default'");
wl(uCalc::@DefaultInstance().EvalStr("val"))

uc.DefineVariable("val = 'uc'");
uc.@IsDefault(true);
wl(uCalc::@DefaultInstance().EvalStr("val"))

New(uCalc, ucB)
ucB.DefineVariable("val = 'ucB'");
ucB.@IsDefault(true);
wl(uCalc::@DefaultInstance().EvalStr("val"))

New(uCalc, ucC)
ucC.DefineVariable("val = 'ucC'");
ucC.@IsDefault(true);
wl(uCalc::@DefaultInstance().EvalStr("val"))

uCalc::DefaultClear();

// The original unnamed default instance is reset so user variable val no longer exists
wl(uCalc::@DefaultInstance().EvalStr("val"))

// The other instances are removed from Default list but remain active
wl(uc.EvalStr("val"))
wl(ucB.EvalStr("val"))
wl(ucC.EvalStr("val"))
```

**Output:**
```
original default
uc
ucB
ucC
Undefined identifier
uc
ucB
ucC
```

---

### Example ID: 62

**Description:** Number of uCalc instances on the default uCalc instance list

**Code:**
```pseudocode
wl(uCalc::@DefaultCount())

uc.@IsDefault(true);
wl(uCalc::@DefaultCount())

New(uCalc, ucB)
ucB.@IsDefault(true);
wl(uCalc::@DefaultCount())

New(uCalc, ucC)
ucC.@IsDefault(true);
wl(uCalc::@DefaultCount())

uCalc::DefaultClear();
wl(uCalc::@DefaultCount())
```

**Output:**
```
1
2
3
4
1
```

---

### Example ID: 64

**Description:** Operator definitions; infix, prefix, postfix, data types, precedence

**Code:**
```pseudocode
uc.DefineOperator("{x} MyOp {y} = x + y", 0); // Infix operator with alphanumeric name
uc.DefineOperator("@@ {number} = number * 2", 0); // Prefix operator with symbolic name
uc.DefineOperator("{val} % = val / 100", 0); // Postfix operator with symbolic name
uc.DefineOperator("{a} times {b} = a * b", uc.ItemOf("*").@Precedence()); // Specifying precedence
uc.DefineOperator("{TextA As String} concat {TextB As String} As String = TextA + TextB", 0); // Specifying types

wl(uc.Eval("5 MyOp 4"))
wl(uc.Eval("@@5"))
wl(uc.Eval("5 %"))
wl(uc.Eval("3 times 5"))
wl(uc.EvalStr("'Hello' concat ' world!'"))
```

**Output:**
```
9
10
0.05
15
Hello world!
```

---

### Example ID: 66

**Description:** Operator ByRef, AnyType, SameTypeAs, Precedence, RightToLeft, callback

**Code:**
```pseudocode
[head]
[callback AssignValueA]
   cb.@uCalc().DataTypeOf(BuiltInType::Integer_64).SetScalar(cb.ArgPtr(1), cb.ArgAddr(2));
   // C++ can do it with pointers instead like the commented line below:
   // *(int64_t *)cb.ArgInt64(1) = cb.ArgInt64(2);
[/callback]
[callback AssignValueB]
   if (cb.ArgItem(1).@DataType().@BuiltInTypeEnum() == BuiltInType::String)
      cb.ArgItem(1).ValueStr(cb.ArgItem(2).ValueStr());
   else
      cb.ArgItem(1).@DataType().SetScalar(cb.ArgItem(1).ValueAddr(), cb.ArgItem(2).ValueAddr());
   end if
[/callback]
[body]

// ByRef approach (only for primitive types only, like double, int, etc., not composite types like strings)
wl("-- ByRef approach --")
uc.DefineOperator("{ByRef variable As AnyType} SetValA {value As SameTypeAs:0} As SameTypeAs:0", uc.ItemOf("=").@Precedence(), Associativity::RightToLeft, AssignValueA);
uc.DefineVariable("MyDbl As Double");
uc.DefineVariable("MyInt As Int");
uc.DefineVariable("MyStr As String");

uc.Eval("MyDbl SetValA 3.14");
uc.Eval("MyInt SetValA Int(3.14 * 10)");

wl("MyDbl: " + uc.EvalStr("MyDbl"))
wl("MyInt: " + uc.EvalStr("MyInt"))

// ByHandle approach
wl("-- ByHandle approach --")
uc.DefineOperator("{ByHandle variable As AnyType} SetValB {ByHandle val As SameTypeAs:0}", uc.ItemOf("=").@Precedence(), Associativity::RightToLeft, AssignValueB);
uc.Eval("MyDbl SetValB 123.456");
uc.Eval("MyInt SetValB Int(555.123)");
uc.Eval("MyStr SetValB 'Hello World'");

wl("MyDbl: " + uc.EvalStr("MyDbl"))
wl("MyInt: " + uc.EvalStr("MyInt"))
wl("MyStr: " + uc.EvalStr("MyStr"))

```

**Output:**
```
-- ByRef approach --
MyDbl: 3.14
MyInt: 31
-- ByHandle approach --
MyDbl: 123.456
MyInt: 555
MyStr: Hello World
```

---

### Example ID: 67

**Description:** Arrays with DefineVariable

**Code:**
```pseudocode
var MyArray = uc.DefineVariable("MyArray[3]");
uc.DefineVariable("MyArrayStr[] = {'aa', 'bb', 'cc'}");

uc.Eval("MyArray[0] = 111; MyArray[1] = 222; MyArray[2] = 333");

wl(uc.EvalStr("MyArray[0]"))
wl(uc.EvalStr("MyArray[1]"))
wl(uc.EvalStr("MyArray[2]"))
wl(uc.EvalStr("MyArrayStr[0]"))
wl(uc.EvalStr("MyArrayStr[1]"))
wl(uc.EvalStr("MyArrayStr[2]"))
wl(MyArray.@Count())
wl(uc.ItemOf("MyArrayStr").@Count())
```

**Output:**
```
111
222
333
aa
bb
cc
3
3
```

---

### Example ID: 70

**Description:** Displays the complete list of default token definitions, showing their type, internal name, and regex pattern.

**Code:**
```pseudocode
// Lists all tokens currently defined for the expression evaluator.

wl("Token Count: ", uc.@ExpressionTokens().@Count())
wl("")
wl("Index  Type  Name: regex")
wl("========================")
var Tokens = uc.@ExpressionTokens();
foreach (var token in Tokens)
   w(Tokens.IndexOf(token))
   wl("  ", token.@Description(), "  ", token.@Name(), ": ", token.@Regex())
end for

// Note that the expression evaluator token list has a few extra tokens,
// related to hex/bin/oct notation, string interpolation, and imaginary number
// notation, which are not found in the default Transformer token list.
```

**Output:**
```
Token Count: 30

Index  Type  Name: regex
========================
0  generic  _token_line: .*
1  generic  _token_catchall: .
2  generic  _token_catchall_utf8_other: [\xf0-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf][\x80-\xbf]|[\xc0-\xdf][\x80-\xbf]
3  generic  _token_punctuation: (--|\.{3}|\xE2\x80\xA6|[!"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~]|\xE2\x80[\x90-\x95])
4  generic  _token_quotechar: ("){3}|"|'
5  generic  _token_quotechar_single: '
6  generic  _token_quotechar_double: "
7  generic  _token_quotechar_tripledouble: """
8  memberaccess  _token_memberaccess: \.
9  generic  _token_variableargs: \.\.\.
10  reducible  _token_reducible2: [-:|+/*^&=%@!`\\<>?#$~]+
11  bracket  _token_parenthesis: \(
12  bracketclose  _token_parenthesis_close: \)
13  bracket  _token_curlybrace: \{
14  bracketclose  _token_curlybrace_close: \}
15  bracket  _token_squarebracket: \[
16  bracketclose  _token_squarebracket_close: \]
17  argseparator  _token_argseparator: ,
18  statementseparator  _token_newline: (?:\r?\n)|\r
19  statementseparator  _token_semicolon: ;
20  literal  _token_string_singlequoted: '([^']*(?:''[^']*)*)'
21  literal  _token_string_doublequoted: "([^"]*(?:""[^"]*)*)"
22  literal  _token_string_tripledoublequoted: """([\s\S]*?)"""
23  whitespace  _token_whitespace: [\t\v ]+
24  reducible  _token_reducible: [-:|+/*^&=%@!`\\<>?]+
25  literal  _token_floatnumber: [0-9]*\.?[0-9]+([eE][+-]?[0-9]+)?
26  alphanumeric  _token_alphanumeric: [a-zA-Z_][a-zA-Z0-9_]*
27  literal  _token_imaginaryunit: #i
28  tokentransform  _token_binaryhexoctalnotation: #[bho][0-9A-F]+
29  tokentransform  _token_stringinterpolationquote: \$['"]
```

---

### Example ID: 71

**Description:** Change characters accepted as alphanumeric in expressions using ExpressionTokens() & Token()

**Code:**
```pseudocode
// (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");
wl(uc.@Error().@Message())
uc.DefineVariable("Variable123 = 222");
wl(uc.@Error().@Message())

wl(uc.@ExpressionTokens()[TokenType::AlphaNumeric].@Regex())
wl(uc.EvalStr("My_Variable"))
wl(uc.EvalStr("Variable123"))
wl("---")

// 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");
wl(uc.@Error().@Message())
uc.DefineVariable("OtherVariable123 = 444");
wl(uc.@Error().@Message())

wl(uc.EvalStr("Other_Variable"))
wl(uc.EvalStr("OtherVariable123 "))
wl(uc.EvalStr("My_Variable"))
wl(uc.EvalStr("Variable123"))
wl("---")

// 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_]*");
wl(uc.EvalStr("My_Variable"))
wl(uc.EvalStr("Variable123"))
```

**Output:**
```
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
```

---

### Example ID: 72

**Description:** Changing accepted tokens with ItemOf().Regex or ExpressionTokens().Token

**Code:**
```pseudocode
// (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");
wl(uc.@Error().@Message())
uc.DefineVariable("Variable123 = 222");
wl(uc.@Error().@Message())

wl(uc.ItemOf("_Token_Alphanumeric").@Regex())
wl(uc.EvalStr("My_Variable"))
wl(uc.EvalStr("Variable123"))
wl("---")

// 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");
wl(uc.@Error().@Message())
uc.DefineVariable("OtherVariable123 = 444");
wl(uc.@Error().@Message())

wl(uc.EvalStr("Other_Variable"))
wl(uc.EvalStr("OtherVariable123 "))
wl(uc.EvalStr("My_Variable"))
wl(uc.EvalStr("Variable123"))
wl("---")

//
// 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_]*");
wl(uc.EvalStr("My_Variable"))
wl(uc.EvalStr("Variable123"))
```

**Output:**
```
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
```

---

### Example ID: 73

**Description:** Using ExpressionTransformer to transform expressions before they are parsed

**Code:**
```pseudocode
var ExprT = uc.@ExpressionTransformer();  // Transformer used for Eval() and Evaluate()

var p1 = ExprT.FromTo("AddUp({x})", "{x}"); // RewindOnChange False by default
var p2 = ExprT.FromTo("AddUp({x}, {y})", "({x} + AddUp({y}))").SetRewindOnChange(true);

wl("p1 RewindOnChange: ", bool(p1.@RewindOnChange()))
wl("p2 RewindOnChange: ", bool(p2.@RewindOnChange()))

wl("")

wl("Input: ", "AddUp(1,2,3,4)")
wl("Transform: ", ExprT.Transform("AddUp(1,2,3,4)"))
wl("Eval: ", uc.Eval("AddUp(1,2,3,4)"))
```

**Output:**
```
p1 RewindOnChange: False
p2 RewindOnChange: True

Input: AddUp(1,2,3,4)
Transform: (1 + (2 + (3 + 4)))
Eval: 10
```

---

### Example ID: 74

**Description:** Raising floating point errors with FloatingPointErrorsToTrap

**Code:**
```pseudocode
wl(uc.@Error().@FloatingPointErrorsToTrap())
wl(uc.EvalStr("1/0"))
wl(uc.EvalStr("0/0"))
wl(uc.EvalStr("5*10^308"))
wl(uc.EvalStr("10^-308/10000"))

wl("--- Raise Div-by-0 ---")
uc.@Error().@FloatingPointErrorsToTrap([c](int)[/c][vb]CInt([/vb]ErrorCode::FloatDivisionByZero[vb])[/vb]);
wl(uc.@Error().@FloatingPointErrorsToTrap())
wl(uc.EvalStr("1/0"))
wl(uc.EvalStr("0/0"))
wl(uc.EvalStr("5*10^308"))
wl(uc.EvalStr("10^-308/10000"))

wl("--- Raise overflow ---")
uc.@Error().@FloatingPointErrorsToTrap([c](int)[/c][vb]CInt([/vb]ErrorCode::FloatOverflow[vb])[/vb]);
wl(uc.@Error().@FloatingPointErrorsToTrap())
wl(uc.EvalStr("1/0"))
wl(uc.EvalStr("0/0"))
wl(uc.EvalStr("5*10^308"))
wl(uc.EvalStr("10^-308/10000"))

wl("--- Raise invalid & underflow ---")
uc.@Error().SetFloatingPointErrorsToTrap(ErrorCode::FloatInvalid, ErrorCode::FloatUnderflow);
wl(uc.@Error().@FloatingPointErrorsToTrap()) // ErrorCode::FloatInvalid + ErrorCode::FloatUnderflow
wl(uc.EvalStr("1/0"))
wl(uc.EvalStr("0/0"))
wl(uc.EvalStr("5*10^308"))
wl(uc.EvalStr("10^-308/10000"))
```

**Output:**
```
0
inf
nan
inf
0
--- Raise Div-by-0 ---
8
Division by 0
nan
inf
0
--- Raise overflow ---
4
Floating point overflow
nan
Floating point overflow
0
--- Raise invalid & underflow ---
18
inf
Invalid operation
inf
Floating point underflow
```

---

### Example ID: 75

**Description:** Checking if a uCalc object is the default with IsDefault

**Code:**
```pseudocode
var Status = uc.DefineVariable("Status As Bool");
wl(bool(Status.ValueBool()))

New(uCalc, MyuCalc)

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

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

wl(uc.EvalStr("$'MyuCalc is the current default? {Status}'"))
```

**Output:**
```
False
MyuCalc is the current default? false
MyuCalc is the current default? true
```

---

### Example ID: 76

**Description:** Setting uCalc default with uCalc.IsDefault()

**Code:**
```pseudocode
New(uCalc, uCalcA)
New(uCalc, uCalcB)
New(uCalc, uCalcC)

uCalcA.DefineVariable("MyVar = 'I was cloned from uCalcA'");
uCalcB.DefineVariable("MyVar = 'I was cloned from uCalcB'");
uCalcC.DefineVariable("MyVar = 'I was cloned from uCalcC'");

uCalcA.@IsDefault(true);
wl(uCalc::@DefaultInstance().EvalStr("MyVar"))

uCalcB.@IsDefault(true);
wl(uCalc::@DefaultInstance().EvalStr("MyVar"))

uCalcC.@IsDefault(true);
wl(uCalc::@DefaultInstance().EvalStr("MyVar"))

wl("---")

// Now unsetting uCalc objects as default
uCalcC.@IsDefault(false);
wl(uCalc::@DefaultInstance().EvalStr("MyVar"))

uCalcB.@IsDefault(false);
wl(uCalc::@DefaultInstance().EvalStr("MyVar"))

uCalcA.@IsDefault(false);
wl(uCalc::@DefaultInstance().EvalStr("MyVar"))


```

**Output:**
```
I was cloned from uCalcA
I was cloned from uCalcB
I was cloned from uCalcC
---
I was cloned from uCalcB
I was cloned from uCalcA
Undefined identifier
```

---

### Example ID: 77

**Description:** ItemOf based on properties

**Code:**
```pseudocode
New(uCalc::Item, Item)
var x = 0;

// Lists the first few funcions defined in uCalc
// For the full list, loop until Item.IsEmpty() or while Item.NotEmpty()
for (x = 0 To 15)
   Item = uc.ItemOf(ItemIs::Function, x);
   wl(Item.@Name())
end for
wl("---")

// List only Prefix and Postfix (operators)
x = 0;
do
   Item = uc.ItemOf(uCalc::Properties(ItemIs::Prefix, ItemIs::Postfix), x);
   x = x + 1;
   wl(Item.@Name())
loop while (Item.NotEmpty())
```

**Output:**
```
abs
acos
acosh
addptr
addressof
anytype
append
append_copy
arg
argcount
asc
asin
asinh
atan
atan2
atanh
---
!
+
-
not
~
```

---

### Example ID: 78

**Description:** Creating uCalc instances

**Code:**
```pseudocode
uc.DefineVariable("x = 123");

New(uCalc, uc1) // Creates a new instance
wl(uc1.EvalStr("x")) // uc1 does not have a variable named x
uc1.Release(); // Releases uc1 if it is no longer needed

var uc2 = uc.Clone(); // Creates new instance that is a clone of uc
wl(uc2.EvalStr("x")) // starts with the value of x obtained from uc
uc2.Eval("x = 456"); // Changes the value of x in uc1 but not uc
wl(uc2.EvalStr("x"))
wl(uc.EvalStr("x")) // The original x in uc remains unchanged
uc2.Release();

// Language specific - auto-releasing uCalc object
[vb]#If False[/vb]
{ // Instances pointed to by neither uCalc1 nor uCalc2 will be released when they go out of scope
   var uCalc1 = new uCalc();
   var uCalc2 = uc.Clone();
   // Call uCalc1.Release() and uCalc2.Release() explicitly if want to release them
}

{ // The instances that both uCalc1 and uCalc2 point to will be released when uCalc1 and uCalc2 go out of scope
   [cs]using var uCalc1 = new uCalc();
   using var uCalc2 = uc.Clone();[/cs]
   [cpp]uCalc uCalc1;
   uCalc uCalc2(uc.Clone());[/cpp]
   // No need for uCalc1.Release() or uCalc2.Release(), they will automatically be released
}
[vb]#End If[/vb]
```

**Output:**
```
Undefined identifier
123
456
123
```

---

### Example ID: 79

**Description:** Defining uCalc Strings and  Expressions in the default uCalc object space

**Code:**
```pseudocode
new(uCalc, ucB)

uc.DefineVariable("x = 111");
ucB.DefineVariable("x = 222");

wl("--- using 'uc' as default ---")
uc.@IsDefault(true);

var(uCalc::String, MyString) = "The variable value is: x";
wl(MyString.Replace("x", "{@Eval: x}"))

var(uCalc::Expression, MyExpression) = "x * 1000";
wl(MyExpression.Evaluate())

New(uCalc::Transformer, MyTransformer)
MyTransformer.@Text("Value is: x");
MyTransformer.FromTo("x", "{@Eval: x}");
wl(MyTransformer.Transform())


wl("--- using 'ucB' as default ---")
ucB.@IsDefault(true);

var(uCalc::String, MyStringB) = "The variable value is: x";
wl(MyStringB.Replace("x", "{@Eval: x}"))

var(uCalc::Expression, MyExpressionB) = "x * 1000";
wl(MyExpressionB.Evaluate())

New(uCalc::Transformer, MyTransformerB)
MyTransformerB.Str("Value is: x");
MyTransformerB.FromTo("x", "{@Eval: x}");
wl(MyTransformerB.Transform())

```

**Output:**
```
--- using 'uc' as default ---
The variable value is: 111
111000
Value is: 111
--- using 'ucB' as default ---
The variable value is: 222
222000
Value is: 222
```

---

### Example ID: 80

**Description:** RaiseErrorOnDivideByZero

**Code:**
```pseudocode
wl(uc.EvalStr("1/0"))
uc.@Error().@TrapOnDivideByZero(true);
wl(uc.EvalStr("1/0"))

wl(uc.EvalStr("Sqrt(-1)"))
uc.@Error().@TrapOnInvalid(true);
wl(uc.EvalStr("Sqrt(-1)"))

wl(uc.EvalStr("5*10^308"))
uc.@Error().@TrapOnOverflow(true);
wl(uc.EvalStr("5*10^308"))

wl(uc.EvalStr("10^-308/10000"))
uc.@Error().@TrapOnUnderflow(true);
wl(uc.EvalStr("10^-308/10000"))
```

**Output:**
```
inf
Division by 0
nan
Invalid operation
inf
Floating point overflow
0
Floating point underflow
```

---

### Example ID: 82

**Description:** Pointer value with ValueAt

**Code:**
```pseudocode
uc.Format("Result = 'Answer: <' + Result + '>'");

var Dbl = uc.DefineVariable("MyDouble = 123.456");

wl(uc.ValueAt(Dbl.ValueAddr(), "Double"))
wl(uc.ValueAt(Dbl.ValueAddr(), BuiltInType::Float_Double))
wl(uc.ValueAt(Dbl.ValueAddr(), BuiltInType::Float_Double, true))


```

**Output:**
```
123.456
123.456
Answer: <123.456>
```

---

### Example ID: 84

**Description:** ArgDbl (same as Arg)

**Code:**
```pseudocode
[head]
[callback MyArea]
var Length = cb.ArgDbl(1); // Same as cb.Arg(1);
var Width = cb.ArgDbl(2); // Same as cb.Arg(2);
cb.Return(Length * Width);
[/callback]
[body]
uc.DefineFunction("Area(x, y)", MyArea);
wl(uc.Eval("Area(3, 4)"))
```

**Output:**
```
12
```

---

### Example ID: 85

**Description:** Return and other type-specific versions of Return

**Code:**
```pseudocode
[head]
[callback BooleanAnd]
   cb.ReturnBool(cb.ArgBool(1) [C]&&[/C][vb]And[/vb] cb.ArgBool(2));
[/callback]
[callback AddInt16]
   [cs]//C# promots Int16 to int for arithmetic hence (Int16) to convert it back 
cb.ReturnInt16((Int16)(cb.ArgInt16(1) + cb.ArgInt16(2)));[/cs]
   [NotCs]cb.ReturnInt16(cb.ArgInt16(1) + cb.ArgInt16(2));[/NotCs]
[/callback]
[callback AddInt32]
   cb.ReturnInt32(cb.ArgInt32(1) + cb.ArgInt32(2));
[/callback]
[callback AddInt64]
   cb.ReturnInt64(cb.ArgInt64(1) + cb.ArgInt64(2));
[/callback]
[body]

uc.DefineFunction("BooleanAnd(x As Bool, y As Bool) As Bool", BooleanAnd);
uc.DefineFunction("AddInt16(x As Int16, y As Int16) As Int16", AddInt16);
uc.DefineFunction("AddInt32(x As Int32, y As Int32) As Int32", AddInt32);
uc.DefineFunction("AddInt64(x As Int64, y As Int64) As Int64", AddInt64);

wl(uc.EvalStr("BooleanAnd(true, false)"))
wl(uc.EvalStr("AddInt16(5.2, 4.1)"))
wl(uc.EvalStr("AddInt32(2, 3)"))
wl(uc.EvalStr("AddInt64(10, 20)"))
```

**Output:**
```
false
9
5
30
```

---

### Example ID: 86

**Description:** Returning a pointer with ReturnPtr

**Code:**
```pseudocode
[head]
[callback GetAddressOf]
   cb.ReturnPtr(cb.ArgItem(1).ValueAddr());
[/callback]
[body]

// This example is for sake of illustration
// There is already a built-in AddressOf() function

uc.DefineFunction("GetAddressOf(ByHandle Variable As AnyType) As SameTypeAs:0 Ptr", GetAddressOf);

uc.DefineVariable("MyVariable = 123.456");
uc.DefineVariable("MyStr = 'Hello world!'");

wl(uc.EvalStr("ValueAt(GetAddressOf(MyVariable))"))
wl(uc.EvalStr("ValueAt(GetAddressOf(MyStr))"))
```

**Output:**
```
123.456
Hello world!
```

---

### Example ID: 87

**Description:** Determining if a data type is compound or not with IsCompound

**Code:**
```pseudocode
wl(bool(uc.DataTypeOf("2 * (3 + 4)").@IsCompound()))
wl(bool(uc.DataTypeOf(" 'Hello ' + 'world!' ").@IsCompound()))
wl(bool(uc.DataTypeOf("3 + 4 * #i").@IsCompound()))
wl(bool(uc.DataTypeOf(BuiltInType::String).@IsCompound()))
wl(bool(uc.DataTypeOf("Bool").@IsCompound()))
```

**Output:**
```
False
True
True
True
False
```

---

### Example ID: 88

**Description:** Data type Reset

**Code:**
```pseudocode
var MyDbl = uc.DefineVariable("MyDbl = 123.456");
var MyStr = uc.DefineVariable("MyStr = 'Hello world!'");
var MyCplx = uc.DefineVariable("MyCplx = 3 + 4 * #i");

wl(uc.EvalStr("MyDbl"))
wl(uc.EvalStr("MyStr"))
wl(uc.EvalStr("MyCplx"))

uc.DataTypeOf("double").Reset(MyDbl.ValueAddr());
uc.DataTypeOf("string").Reset(MyStr.ValueAddr()); // empty string ""
uc.DataTypeOf("complex").Reset(MyCplx.ValueAddr());

wl(uc.EvalStr("MyDbl"))
wl(uc.EvalStr("MyStr"))
wl(uc.EvalStr("MyCplx"))


```

**Output:**
```
123.456
Hello world!
3+4i
0

0+0i
```

---

### Example ID: 89

**Description:** Sets a data type as the default

**Code:**
```pseudocode
wl(bool(uc.DataTypeOf("double").@IsDefault()))
wl(bool(uc.DataTypeOf("int64").@IsDefault()))
wl(uc.@DefaultDataType().@Name())
wl("---")

uc.DataTypeOf("int64").@IsDefault(true);

wl(bool(uc.DataTypeOf("double").@IsDefault()))
wl(bool(uc.DataTypeOf("int64").@IsDefault()))
wl(uc.@DefaultDataType().@Name())
wl("---")

uc.DataTypeOf("int64").@IsDefault(false);

wl(bool(uc.DataTypeOf("double").@IsDefault()))
wl(bool(uc.DataTypeOf("int64").@IsDefault()))
wl(uc.@DefaultDataType().@Name())
```

**Output:**
```
True
False
double
---
False
True
int64
---
True
False
double
```

---

### Example ID: 90

**Description:** SetScalar

**Code:**
```pseudocode
var MyVar1 = uc.DefineVariable("MyVar1 = 123.456");
var MyVar2 = uc.DefineVariable("MyVar2 = 654.321");
var MyStr1 = uc.DefineVariable("MyStr1 = 'First string'");
var MyStr2 = uc.DefineVariable("MyStr2 = 'Second string'");

uc.DataTypeOf("double").SetScalar(MyVar1.ValueAddr(), MyVar2.ValueAddr());
uc.DataTypeOf("string").SetScalar(MyStr1.ValueAddr(), MyStr2.ValueAddr());

wl(uc.EvalStr("MyVar1")) // Now contains value copied from MyVar2
wl(uc.EvalStr("MyStr1")) // Now contains value copied from MyStr2
```

**Output:**
```
654.321
Second string
```

---

### Example ID: 91

**Description:** SwapScalarValues

**Code:**
```pseudocode
var MyVar1 = uc.DefineVariable("MyVar1 = 123.456");
var MyVar2 = uc.DefineVariable("MyVar2 = 654.321");
var MyStr1 = uc.DefineVariable("MyStr1 = 'First string'");
var MyStr2 = uc.DefineVariable("MyStr2 = 'Second string'");

wl(uc.EvalStr("MyVar1"))
wl(uc.EvalStr("MyVar2"))
wl(uc.EvalStr("MyStr1"))
wl(uc.EvalStr("MyStr2"))
wl("---")

uc.DataTypeOf("double").SwapScalarValues(MyVar1.ValueAddr(), MyVar2.ValueAddr());
uc.DataTypeOf("string").SwapScalarValues(MyStr1.ValueAddr(), MyStr2.ValueAddr());

wl(uc.EvalStr("MyVar1")) // Values of MyVar1 and MyVar2 are now swapped
wl(uc.EvalStr("MyVar2"))
wl(uc.EvalStr("MyStr1")) // Values of MyStr1 and MyStr2 are now swapped
wl(uc.EvalStr("MyStr2"))
```

**Output:**
```
123.456
654.321
First string
Second string
---
654.321
123.456
Second string
First string
```

---

### Example ID: 92

**Description:** Using ToString to convert a value to a string

**Code:**
```pseudocode
wl(uc.DataTypeOf(BuiltInType::Integer_8).ToString("-1"))
wl(uc.DataTypeOf(BuiltInType::Integer_8u).ToString("-1"))
wl(uc.DataTypeOf(BuiltInType::Integer_16u).ToString("-1"))
wl(uc.DataTypeOf(BuiltInType::Boolean).ToString("-1"))
wl(uc.DataTypeOf(BuiltInType::String).ToString("-1"))
```

**Output:**
```
-1
255
65535
true
-1
```

---

### Example ID: 93

**Description:** EvaluateBool, also ValueStr which converts numeric value to string

**Code:**
```pseudocode

var VariableX = uc.DefineVariable("x");
var ParsedExpr = uc.Parse("x > 3"); // The > operation returns a Boolean instead of the default floating point

for (double x = 1 to 5)
   VariableX.Value(x);
   wl("x = ", VariableX.ValueStr(), "  x > 3 is ", bool(ParsedExpr.EvaluateBool()))
end for

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
x = 1  x > 3 is False
x = 2  x > 3 is False
x = 3  x > 3 is False
x = 4  x > 3 is True
x = 5  x > 3 is True
```

---

### Example ID: 94

**Description:** Expression constructor

**Code:**
```pseudocode
uCalc::@DefaultInstance().DefineVariable("x = 1.2");
uc.DefineVariable("x = 3.2");

New(uCalc::Expression, MyExprA)
New(uCalc::Expression, MyExprB("x+4.25"))
New(uCalc::Expression, MyExprC("x+4.25", uCalc::@DefaultInstance().DataTypeOf("int")))
New(uCalc::Expression, MyExprD(uc, "x+4.25"))

MyExprA.Parse("x*100");

wl(MyExprA.Evaluate())
wl(MyExprB.Evaluate())
wl(MyExprC.Evaluate())
wl(MyExprD.Evaluate())

// Release expressions when no longer needed (see other example for auto-release)
MyExprA.Release();
MyExprB.Release();
MyExprC.Release();
MyExprD.Release();
```

**Output:**
```
120
5.45
5
7.45
```

---

### Example ID: 96

**Description:** Evaluate() auto-conversion

**Code:**
```pseudocode
// The int return value type in MyExprB is converted to
// Double with .Evaluate(), but not with .EvaluateDbl()
var MyExprA = uc.Parse("3.2 + 5.2");
var MyExprB = uc.Parse("int(3.2 + 5.2)");

wl(MyExprA.Evaluate())
wl(bool(MyExprA.EvaluateDbl() == 8.4))
wl(MyExprB.Evaluate())
wl(bool(MyExprB.EvaluateDbl() == 8))
```

**Output:**
```
8.4
True
8
False
```

---

### Example ID: 97

**Description:** Gets uCalc object associated with an expression

**Code:**
```pseudocode
var MyExpr = uc.Parse("5+4");

wl(MyExpr.Evaluate())

MyExpr.@uCalc().Format("Result = 'Answer = ' + Result");

wl(MyExpr.EvaluateStr())
```

**Output:**
```
9
Answer = 9
```

---

### Example ID: 98

**Description:** uCalc.Item constructor

**Code:**
```pseudocode

// Note that x is defined in the default instance
// while f(x) is defined in the uc instance.
New(uCalc::Item, MyVar("Variable: x = 123"))
New(uCalc::Item, MyFunc(uc, "Function: f(x) = x^2"))

wl(uCalc::@DefaultInstance().Eval("x"))
wl(uc.Eval("f(5)"))

MyVar.Release();
MyFunc.Release();
  
```

**Output:**
```
123
25
```

---

### Example ID: 99

**Description:** Language-specific auto-releasing of Item object

**Code:**
```pseudocode
// Language specific - auto-releasing Item object
wl("auto-releasing Item (language-specific)")
[vb]#If False[/vb]
{ // MyVar resources will NOT be released when MyVar goes out of scope
   var MyVar = new uCalc::Item("Variable: x = 123");
   // Call MyVar.Release() explicitly if want to release it here
}

{ // MyVar resouces will be released automatically when MyVar goes of scope
   [cs]using var MyVar = new uCalc.Item("Variable: x = 123");[/cs]
   [cpp]uCalc::Item MyVar("Variable: x = 123");[/cpp]
   // No need for MyVar.Release(), it will automatically be released
}
[vb]#End If[/vb]
```

**Output:**
```
auto-releasing Item (language-specific)
```

---

### Example ID: 100

**Description:** Setting a token data type

**Code:**
```pseudocode

// This example makes the # character behave the same way as quotes
uc.@ExpressionTokens().Add("#([^#]*)#", TokenType::Literal, "", 1).@DataType(uc.DataTypeOf("String"));
wl(uc.EvalStr("#Hello # + #World#"))
```

**Output:**
```
Hello World
```

---

### Example ID: 101

**Description:** Changing an item's property

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("x = 100");
wl(uc.EvalStr("x"))

uc.EvalStr("x = 200");
wl(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
wl(uc.EvalStr("x")) // x retains the previous value




```

**Output:**
```
100
200
200
```

---

### Example ID: 102

**Description:** Using ValuePtr

**Code:**
```pseudocode
var xVar = uc.DefineVariable("x = 123");
var xVarPtr = uc.DefineVariable("xPtr As Double Ptr = AddressOf(x)");

wl(bool((xVarPtr.ValuePtr() == xVar.ValueAddr())))
```

**Output:**
```
True
```

---

### Example ID: 103

**Description:** Using ValueStr()

**Code:**
```pseudocode
var MyStr = uc.DefineVariable("MyStr As String");
var MyDbl = uc.DefineVariable("MyDbl As Double");
var MyCplx = uc.DefineVariable("MyCplx As Complex");
var MyBool = uc.DefineVariable("MyBool As Boolean");

MyStr.ValueStr("Hello world!");
MyDbl.ValueStr("123.456");
MyCplx.ValueStr("3+4*#i");
MyBool.ValueStr("True");

wl(uc.EvalStr("$'MyStr = {MyStr}'"))
wl(uc.EvalStr("$'MyDbl = {MyDbl}'"))
wl(uc.EvalStr("$'MyCplx = {MyCplx}'"))
wl(uc.EvalStr("$'MyBool = {MyBool}'"))
wl("---")
wl(MyStr.ValueStr())
wl(MyDbl.ValueStr())
wl(MyCplx.ValueStr())
wl(MyBool.ValueStr())
```

**Output:**
```
MyStr = Hello world!
MyDbl = 123.456
MyCplx = 3+4i
MyBool = true
---
Hello world!
123.456
3+4i
true
```

---

### Example ID: 105

**Description:** How to extract text that appears after a specific pattern using the String.After() method.

**Code:**
```pseudocode
var(uCalc::String, s) = "This is just a test";
wl(s.After("is"))

s = "/* if else */ if (x > 100) y = x * 2; else if(x == 5) y = x - 1;";
wl(s.After("if ({cond})"))
wl(s.After("if ({cond})").After("if ({cond})"))
wl(s.After("if ({cond})", 2)) // Finds text after 2nd match (same as above)
wl(s.After("NonExistingPattern")) // Nothing to display on this line
wl("----")

```

**Output:**
```
 just a test
 y = x * 2; else if(x == 5) y = x - 1;
 y = x - 1;
 y = x - 1;

----
```

---

### Example ID: 107

**Description:** uCalc.Items

**Code:**
```pseudocode
// Note: Some items in this list (like bool, or int*) appear more than once or out of chronological
// order because they are aliases (like bool, which is also an alias for boolean)
foreach(var item in uc.@Items())
   wl(item.@Name())
end foreach
```

**Output:**
```
!
%
&
&&
*
+
,
-
/
<
<<
<=
<>
=
==
>
>=
>>
\
^
_enduserformattedoutput
_newline
_token_alphanumeric
_token_argseparator
_token_binaryhexoctalnotation
_token_catchall
_token_catchall_utf8_other
_token_curlybrace
_token_curlybrace_close
_token_floatnumber
_token_imaginaryunit
_token_line
_token_memberaccess
_token_newline
_token_parenthesis
_token_parenthesis_close
_token_punctuation
_token_quotechar
_token_quotechar_double
_token_quotechar_single
_token_quotechar_tripledouble
_token_reducible
_token_reducible2
_token_semicolon
_token_squarebracket
_token_squarebracket_close
_token_string_doublequoted
_token_string_singlequoted
_token_string_tripledoublequoted
_token_stringinterpolationquote
_token_variableargs
_token_whitespace
_ucalc_lib_is32
_ucalc_lib_is64
_ucalc_lib_release_timestamp
_ucalc_lib_version
abs
acos
acosh
addptr
addressof
and
andalso
anytype
append
append_copy
arg
argcount
asc
asin
asinh
atan
atan2
atanh
back
baseconvert
bin
bitand
bitor
bool
bool
int8u
c_str
cbrt
ceil
chr
clear
compare
complex
conj
contains
copysign
cos
cosh
define
doloop
double
endswith
erase
erase_copy
erf
erfc
error
eval
evalstr
evaluate
evaluateint
evaluatestr
exp
exp2
expm1
exprptr
fabs
false
fdim
file
filesize
fill
find_first_not_of
find_first_of
find_last_not_of
find_last_of
single
floor
fmax
fmin
fmod
forloop
format
fpclassify
frac
frexp
fromto
goto
hex
hypot
iif
ilogb
imag
indexof
inf
insert
insert_copy
int
int16
int16u
int
int32u
int64
int64u
int8
int8u
int
isfinite
isinf
isnan
isnormal
lastindexof
lastrandomnumber
lcase
ldexp
length
lgamma
llrint
llround
log
log10
log1p
log2
logb
lrint
lround
ltrim
max
min
mod
modf
nan
nearbyint
nextafter
nexttoward
norm
not
oct
omnitype
or
orelse
padleft
padright
parse
pointer
polar
pop
pow
precedence
proj
push
rand
randfromsameseed
randomnumber
randomseed
real
remainder
remquo
repeat
replace
replace_copy
reset
rint
round
rtrim
sametypeas
scalbln
scalbn
setvar
sgn
signbit
sin
single
sinh
size_t
sizeof
sort
sqr
sqrt
startswith
str
string
substr
subtractptr
swap
tan
tanh
tgamma
trim
true
trunc
ucalcinstance
ucase
valueat
valueattype
void
xor
|
||
~
```

---

### Example ID: 108

**Description:** ListOfItem with name / property

**Code:**
```pseudocode
wl("Items with the Prefix property")
wl("------------------------------")
foreach(var item in uc.GetItems(ItemIs::Prefix))
   wl(item.@Name())
end foreach

wl("")
wl("Different versions of the + operator")
wl("------------------------------------")
foreach(var item in uc.GetItems("+"))
   wl(item.@Text())
end foreach
```

**Output:**
```
Items with the Prefix property
------------------------------
!
+
-
not
~

Different versions of the + operator
------------------------------------
Operator: 70 +{x}
Operator: 50 {x} + {y}
Operator: 50 {x As Int} + {y As Int} As Int
Operator: 50 {x As String} + {y As String} As String
Operator: 50 {x As Complex} + {y As Complex} As Complex
Operator: 50 {ByHandle x As AnyType Ptr} + {y As Int} As SameTypeAs:0 Ptr
Operator: 50 {ByHandle x As AnyType} + {ByHandle y As String} As String
Operator: 50 {ByHandle x As String} + {ByHandle y As AnyType} As String
```

---

### Example ID: 109

**Description:** ListOfDataTypes

**Code:**
```pseudocode
foreach(var Item in uc.ListOfDataTypes())
   wl(Item.@Name())
end foreach

```

**Output:**
```
anytype
bool
bool
int8u
complex
double
single
int
int16
int16u
int
int32u
int64
int64u
int8
int8u
int
omnitype
pointer
sametypeas
single
size_t
string
void
```

---

### Example ID: 110

**Description:** How to find matched patterns while skipping commented text using SkipOver().

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("int result = (x + 3) * 2 - (y - 7 / z) * (5 ^ a + 10); /* (x + y) */");

// Capture standard blocks surrounded by parentheses
t.Pattern("({expr})");

// Instruct the transformer to ignore any text inside C-style block comments.
// This prevents the commented "(x + y)" from being falsely counted as a match.
t.SkipOver("/* {etc} */"); // commented text between /* */ is skipped

t.Find();
wl(t.@Matches().Count())
```

**Output:**
```
3
```

---

### Example ID: 111

**Description:** Returns Start and End positions of Transformer matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<br><h1>First</h1>Blah Blah<br>Testing<br><h2>Second</h2>");
//         ^             ^                       ^              ^
//     012345678901234567890123456789012345678901234567890123456789
//     0         10        20        30        40        50
// Carrets (^) point to Start and End locations of the matches

wl(t.@Text())
wl("")

t.Pattern("<{tag}>{etc}</{tag}>");
t.Find();
var Matches = t.@Matches();

wl(Matches[0].@Text())
wl("Start pos: ", Matches[0].@StartPosition())
wl("End pos: ", Matches[0].@EndPosition())
wl("Length: ", Matches[0].@Length())
wl("")

wl(Matches[1].@Text())
wl("Start pos: ", Matches[1].@StartPosition())
wl("End pos: ", Matches[1].@EndPosition())
wl("Length: ", Matches[1].@Length())
```

**Output:**
```
<br><h1>First</h1>Blah Blah<br>Testing<br><h2>Second</h2>

<h1>First</h1>
Start pos: 4
End pos: 18
Length: 14

<h2>Second</h2>
Start pos: 42
End pos: 57
Length: 15
```

---

### Example ID: 112

**Description:** Filters matches by rule; FilterByRule, Matches.Str, Matches.Count

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b><p>My paragraph</p>");

var AnyOtherTag = t.Pattern("<{tag}>{text}</{tag}>");
var BoldTag = t.Pattern("<b>{text}</b>");
var H3Tag = t.Pattern("<h3>{text}</h3>");
t.Find();

wl("All matches -- count = ", t.@Matches().Count())
wl("----------------------")
wl(t.@Matches())
wl("")

wl("Only BoldTag matches -- count = ", BoldTag.@Matches().Count())
wl("-------------------------------")
wl(BoldTag.@Matches())
wl("")

wl("Only H3Tag matches -- count = ", H3Tag.@Matches().Count())
wl("-----------------------------")
wl(H3Tag.@Matches())
```

**Output:**
```
All matches -- count = 5
----------------------
<h3>Title</h3>
<b>Bold statement</b>
<h3>Title B</h3>
<b>Other text</b>
<p>My paragraph</p>

Only BoldTag matches -- count = 2
-------------------------------
<b>Bold statement</b>
<b>Other text</b>

Only H3Tag matches -- count = 2
-----------------------------
<h3>Title</h3>
<h3>Title B</h3>
```

---

### Example ID: 113

**Description:** Using IndexOf() in Matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b><p>My paragraph</p>");
//     ^             ^                    ^               ^                ^
//     012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
//     0         10        20        30        40        50        60        70        80
// Carrets (^) point to Start locations of the matches

var AnyOtherTag = t.Pattern("<{tag}>{text}</{tag}>");
var BoldTag = t.Pattern("<b>{text}</b>");
var H3Tag = t.Pattern("<h3>{text}</h3>");
t.Find();

wl("IndexOf   StartPos   Match")
wl("")

wl("All Matches")
wl("-----------")
foreach(var match in t.@Matches()) 
   wl(t.@Matches().IndexOf(match.@StartPosition()), "         ", match.@StartPosition(), "          ", match.@Text())
end for
wl("")

wl("Bold Matches")
wl("------------")
foreach(var BoldMatch in BoldTag.@Matches()) 
   wl(t.@Matches().IndexOf(BoldMatch.@StartPosition()), "         ", BoldMatch.@StartPosition(), "          ", BoldMatch.@Text())
end for
wl("")

wl("H3 Matches")
wl("----------")
foreach(var H3Match in H3Tag.@Matches()) 
   wl(t.@Matches().IndexOf(H3Match.@StartPosition()), "         ", H3Match.@StartPosition(), "          ", H3Match.@Text())
end for
wl("")

wl("Other Matches")
wl("-------------")
foreach(var AnyOtherMatch in AnyOtherTag.@Matches()) 
   wl(t.@Matches().IndexOf(AnyOtherMatch.@StartPosition()), "         ", AnyOtherMatch.@StartPosition(), "          ", AnyOtherMatch.@Text())
end for
```

**Output:**
```
IndexOf   StartPos   Match

All Matches
-----------
0         0          <h3>Title</h3>
1         14          <b>Bold statement</b>
2         35          <h3>Title B</h3>
3         51          <b>Other text</b>
4         68          <p>My paragraph</p>

Bold Matches
------------
1         14          <b>Bold statement</b>
3         51          <b>Other text</b>

H3 Matches
----------
0         0          <h3>Title</h3>
2         35          <h3>Title B</h3>

Other Matches
-------------
4         68          <p>My paragraph</p>
```

---

### Example ID: 114

**Description:** Matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<h3>Title</h3><b>Bold statement</b><!--<h3>Title B</h3>--><b>Other text</b><p>My paragraph</p>");
//     0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456
//     0         10        20        30        40        50        60        70        80        90
//     ^             ^                                           ^                ^                  ^
// Carrets (^) represent starting and ending point of the matches

t.Pattern("<{tag}>{text}</{tag}>");
t.Pattern("<b>{text}</b>");
t.Pattern("<h3>{text}</h3>");
t.SkipOver("<!--{text}-->");
t.Find();

foreach(var match in t.@Matches())
   wl(match.@Text())
   wl("Start pos: ", match.@StartPosition())
   wl("End pos: ", match.@EndPosition())
   wl("Length: ", match.@Length())
   wl("")
end foreach
```

**Output:**
```
<h3>Title</h3>
Start pos: 0
End pos: 14
Length: 14

<b>Bold statement</b>
Start pos: 14
End pos: 35
Length: 21

<b>Other text</b>
Start pos: 58
End pos: 75
Length: 17

<p>My paragraph</p>
Start pos: 75
End pos: 94
Length: 19
```

---

### Example ID: 118

**Description:** How to assign and retrieve descriptions for specific transformation patterns using SetDescription().

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b><p>My paragraph</p>");

var AnyOtherTag = t.Pattern("<{tag}>{text}</{tag}>").SetDescription("other kind of tag");
var BoldTag = t.Pattern("<b>{text}</b>").SetDescription("bold tag");
var H3Tag = t.Pattern("<h3>{text}</h3>").SetDescription("h3 tag");
t.Find();

foreach(var match in t.@Matches())
   wl(match.@Text() + "   Description: " + match.@Rule().@Description())
end foreach
```

**Output:**
```
<h3>Title</h3>   Description: h3 tag
<b>Bold statement</b>   Description: bold tag
<h3>Title B</h3>   Description: h3 tag
<b>Other text</b>   Description: bold tag
<p>My paragraph</p>   Description: other kind of tag
```

---

### Example ID: 120

**Description:** How to dynamically enable or disable transformation rules using the Active property.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b>");

var BoldTag = t.Pattern("<b>{text}</b>");
var H3Tag = t.Pattern("<h3>{text}</h3>");
t.Find();


wl(t.@Matches().@Text())
wl("")

BoldTag.@Active(false);
wl("BoldTag.Active(): ", bool(BoldTag.@Active()))
wl("-----------------------")
t.Find();
wl(t.@Matches().@Text())
wl("")

BoldTag.@Active(true);
wl("BoldTag.Active(): ", bool(BoldTag.@Active()))
wl("----------------------")

t.Find();
wl(t.@Matches().@Text())
wl("")

```

**Output:**
```
<h3>Title</h3>
<b>Bold statement</b>
<h3>Title B</h3>
<b>Other text</b>

BoldTag.Active(): False
-----------------------
<h3>Title</h3>
<h3>Title B</h3>

BoldTag.Active(): True
----------------------
<h3>Title</h3>
<b>Bold statement</b>
<h3>Title B</h3>
<b>Other text</b>
```

---

### Example ID: 121

**Description:** BracketSensitive

**Code:**
```pseudocode
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
wl("BracketSensitive: ", bool(Pattern.@BracketSensitive()))
wl("----------------------")
t.Find();
wl(t.@Matches().@Text())
wl("")

Pattern.@BracketSensitive(false);
wl("BracketSensitive: ", bool(Pattern.@BracketSensitive()))
wl("-----------------------")

t.Find();
wl(t.@Matches().@Text())
wl("")

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} )");

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


```

**Output:**
```
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 )
```

---

### Example ID: 122

**Description:** CaseSensitive

**Code:**
```pseudocode
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);
wl("CaseSensitive: ", bool(Pattern.@CaseSensitive()))
wl("-------------------")
t.Find();
wl(t.@Matches().@Text())
wl("")

Pattern.@CaseSensitive(false);
wl("CaseSensitive: ", bool(Pattern.@CaseSensitive()))
wl("--------------------")
t.Find();
wl(t.@Matches().@Text())
```

**Output:**
```
CaseSensitive: True
-------------------
StArT a b c FinISH

CaseSensitive: False
--------------------
start x y z finish
StArT a b c FinISH
START 1 2 3 FINISH
```

---

### Example ID: 123

**Description:** Focusable to toggle pattern matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b>");

var BoldTag = t.Pattern("<b>{text}</b>").SetFocusable(true);
var H3Tag = t.Pattern("<h3>{text}</h3>").SetFocusable(true);
t.Find();

wl(t.GetMatches(MatchesOption::FocusableOnly).@Text())
wl("")

BoldTag.@Focusable(false);
wl("BoldTag.Focusable(): ", bool(BoldTag.@Focusable()))
wl("--------------------------")
// t.Find(); // A Find operation does not have to be executed again
wl(t.GetMatches(MatchesOption::FocusableOnly).@Text())
wl("")

BoldTag.@Focusable(true);
wl("BoldTag.Focusable(): ", bool(BoldTag.@Focusable()))
wl("--------------------------")

//t.Find(); // A Find operation does not have to be executed again
wl(t.GetMatches(MatchesOption::FocusableOnly).@Text())
wl("")
```

**Output:**
```
<h3>Title</h3>
<b>Bold statement</b>
<h3>Title B</h3>
<b>Other text</b>

BoldTag.Focusable(): False
--------------------------
<h3>Title</h3>
<h3>Title B</h3>

BoldTag.Focusable(): True
--------------------------
<h3>Title</h3>
<b>Bold statement</b>
<h3>Title B</h3>
<b>Other text</b>
```

---

### Example ID: 125

**Description:** Using SkipOver() to ignore XML-style comments

**Code:**
```pseudocode
// StatementSensitive() is set to false so that ";" and newline are not treated as special

var t = uc.NewTransformer();
wl("StatementSensitive: ", bool(t.@DefaultRuleSet().@StatementSensitive()))
wl("Setting StatementSensitive to False")

t.@DefaultRuleSet().@StatementSensitive(false); // so that newline does not behave as a statement separator

wl("StatementSensitive: ", bool(t.@DefaultRuleSet().@StatementSensitive()))
wl("")

var Content =
[verbatim]
<nav aria-label="Main navigation">
  <ul>
    <li><a href="#intro">Intro</a></li>
    <li><a href="#examples">Examples</a></li>
    <!-- <li><a href="#contact">Contact</a></li> -->
  </ul>
</nav>

<!-- 
<h2>Ingredients</h2>
<ul>
  <li>3 cups flour</li>
  <li>1.5 cups water</li>
  <li>1 tsp salt</li>
</ul>
-->

<nav aria-label="Chapter navigation">
    <ul>
      <li><a href="#one">One</a></li>
      <li><a href="#two">Two</a></li>
      <li><a href="#three">Three</a></li>
    </ul>
</nav>
[/verbatim];

t.Str(Content);
var Pattern = t.Pattern("<li>{item}</li>");
t.Find();
wl(t.@Matches().@Text())
wl("")

wl("<!-- Skip over commented lines -->")
wl("----------------------------------")
t.SkipOver("<!-- {comment} -->");
t.Find();
wl(t.@Matches().@Text())
wl("")

```

**Output:**
```
StatementSensitive: True
Setting StatementSensitive to False
StatementSensitive: False

<li><a href="#intro">Intro</a></li>
<li><a href="#examples">Examples</a></li>
<li><a href="#contact">Contact</a></li>
<li>3 cups flour</li>
<li>1.5 cups water</li>
<li>1 tsp salt</li>
<li><a href="#one">One</a></li>
<li><a href="#two">Two</a></li>
<li><a href="#three">Three</a></li>

<!-- Skip over commented lines -->
----------------------------------
<li><a href="#intro">Intro</a></li>
<li><a href="#examples">Examples</a></li>
<li><a href="#one">One</a></li>
<li><a href="#two">Two</a></li>
<li><a href="#three">Three</a></li>
```

---

### Example ID: 126

**Description:** LocalTransformer, HasLocalTransformer, IsChildRule

**Code:**
```pseudocode
// Note the change in section/div/h2
var t = uc.NewTransformer();

var rule = t.Pattern("<section>{body}</section>").SetStatementSensitive(false);
var section = rule.@LocalTransformer();
section.FromTo("<h2>{text}</h2>", "<h1>====> {@Eval: UCase(text)} <====</h1>");
section.SkipOver("&{entity};");
var ch = section.FromTo("<p>{text}</p>", "<p>SELECTED: {text}</p>");

wl("Has a local transformer: ", bool(rule.@HasLocalTransformer()))
wl("rule is a child rule: ", bool(rule.@IsChildRule()))
wl("ch is a child rule: ", bool(ch.@IsChildRule()))

var HtmlText = 
[verbatim]
<div class="article" data-id="1">
  <h2>Article One</h2>
  <p>This is the first article.</p>
</div>

<div class="article" data-id="2">
  <h2>Article Two</h2>
  <p>This is the second article.</p>
</div>

<section>
  <div class="article" data-id="3">
    <h2>Article Three</h2>
    <p>This one is inside a &lt;section&gt;.</p>
  </div>
</section>

<div class="article" data-id="4">
  <h2>Article Four</h2>
  <p>This is the fourth article.</p>
</div>
[/verbatim];

t.@Text(HtmlText);
t.Transform();
wl(t.@Text())


```

**Output:**
```
Has a local transformer: True
rule is a child rule: False
ch is a child rule: True

<div class="article" data-id="1">
  <h2>Article One</h2>
  <p>This is the first article.</p>
</div>

<div class="article" data-id="2">
  <h2>Article Two</h2>
  <p>This is the second article.</p>
</div>

<section>
  <div class="article" data-id="3">
    <h1>====> ARTICLE THREE <====</h1>
    <p>SELECTED: This one is inside a &lt;section&gt;.</p>
  </div>
</section>

<div class="article" data-id="4">
  <h2>Article Four</h2>
  <p>This is the fourth article.</p>
</div>
```

---

### Example ID: 127

**Description:** Maximum, GlobalMaximum

**Code:**
```pseudocode
var FruitsXML = 
[verbatim]
<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' />
  <Fruit CommonName='Strawberry' ScientificName='Fragaria × ananassa' />
  <Fruit CommonName='Pineapple' ScientificName='Ananas comosus' />
  <Fruit CommonName='Mango' ScientificName='Mangifera indica' />
  <Fruit CommonName='Blueberry' ScientificName='Vaccinium corymbosum' />
  <Fruit CommonName='Rambutan' ScientificName='Nephelium lappaceum' />
  <Fruit CommonName='Salak (Snake Fruit)' ScientificName='Salacca zalacca' />
  <Fruit CommonName='Jabuticaba' ScientificName='Plinia cauliflora' />
  <Fruit CommonName='Watermelon' ScientificName='Citrullus lanatus' />
</Fruits>
[/verbatim];

uc.DefineVariable("x");
var t = uc.NewTransformer();
var FruitsTag = t.FromTo("<Fruits>", "List of fruits");
var Fruit = t.FromTo("CommonName={@string:name}", "{@Eval: x++}. {name}");

uc.Eval("x = 1");
Fruit.@Maximum(10);
t.Filter(FruitsXML);
wl("Maximum = ", Fruit.@Maximum())
wl("Matches count: ", t.@Matches().Count()) // 1 for FruitsTag occurrence 
wl("")
wl(t.@Matches())
wl("")
wl("===============")

uc.Eval("x = 1");
Fruit.@Maximum(20);
t.Filter(FruitsXML);
wl("Maximum = ", Fruit.@Maximum())
wl("Matches count: ", t.@Matches().Count()) // 1 for FruitsTag plus 12 fruits
wl("")
wl(t.@Matches())
wl("")
wl("===============")

uc.Eval("x = 1");
Fruit.@GlobalMaximum(10); // Notice "List of fruits" will not show
t.Filter(FruitsXML);
wl("MaximumAND = ", Fruit.@GlobalMaximum())
wl("Matches count: ", t.@Matches().Count()) // Even FruitsTage won't be counted
wl("")
wl(t.@Matches())
wl("===============")

uc.Eval("x = 1");
Fruit.@GlobalMaximum(20);
t.Filter(FruitsXML);
wl("MaximumAND = ", Fruit.@GlobalMaximum())
wl("Matches count: ", t.@Matches().Count())
wl("")
wl(t.@Matches())

```

**Output:**
```
Maximum = 10
Matches count: 1

List of fruits

===============
Maximum = 20
Matches count: 13

List of fruits
1. Apple
2. Banana
3. Orange
4. Grapes
5. Strawberry
6. Pineapple
7. Mango
8. Blueberry
9. Rambutan
10. Salak (Snake Fruit)
11. Jabuticaba
12. Watermelon

===============
MaximumAND = 10
Matches count: 0


===============
MaximumAND = 20
Matches count: 13

List of fruits
1. Apple
2. Banana
3. Orange
4. Grapes
5. Strawberry
6. Pineapple
7. Mango
8. Blueberry
9. Rambutan
10. Salak (Snake Fruit)
11. Jabuticaba
12. Watermelon
```

---

### Example ID: 130

**Description:** Rule Name

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<b>(5+4)</b> this and that etc");
var a = t.Pattern("<{tg}>");
var b = t.Pattern("This {body} That");
var c = t.Pattern("etc");
var d = t.Pattern("({expr})");

t.Filter();
wl("--- Matches ---")
wl(t.@Matches().@Text())
wl("--- Pattern names ---")
wl(a.@Name())
wl(b.@Name())
wl(c.@Name())
wl(d.@Name())
wl("--- Pattern defs ---")
wl(a.@Pattern())
wl(b.@Pattern())
wl(c.@Pattern())
wl(d.@Pattern())
```

**Output:**
```
--- Matches ---
<b>
(5+4)
</b>
this and that
etc
--- Pattern names ---
<
this
etc
(
--- Pattern defs ---
<{tg}>
This {body} That
etc
({expr})
```

---

### Example ID: 131

**Description:** Rule NextOverload and Tag

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("Testing (a b c) Testing x y z! Testing 1 2 3.");

var Pattern1 = t.Pattern("Testing {etc}.").SetTag(111);
var Pattern2 = t.Pattern("Testing {etc}!").SetTag(222);
var Pattern3 = t.Pattern("Testing ({etc})").SetTag(333);

t.Find();
wl("--- Matches ---")
wl(t.@Matches().@Text())
wl("--- Patterns ---")
wl(Pattern1.@Pattern())
wl(Pattern2.@Pattern())
wl(Pattern3.@Pattern())
wl("---- Tags ----")
wl(Pattern1.@Tag())
wl(Pattern2.@Tag())
wl(Pattern3.@Tag())
wl("-- Overload Tags --")
// Note that most recently defined patterns come first
wl(Pattern3.NextOverload().@Tag())
wl(Pattern2.NextOverload().@Tag())
wl(Pattern1.NextOverload().@Tag())


```

**Output:**
```
--- Matches ---
Testing (a b c)
Testing x y z!
Testing 1 2 3.
--- Patterns ---
Testing {etc}.
Testing {etc}!
Testing ({etc})
---- Tags ----
111
222
333
-- Overload Tags --
222
111
0
```

---

### Example ID: 132

**Description:** ParentTransformer

**Code:**
```pseudocode
var Txt = "Test a b c. x y z";

var FirstTransform = uc.NewTransformer().SetText(Txt).SetDescription("First Transformer");
var aaa = FirstTransform.FromTo("Test {etc}.", "[{etc}]");

var SecondTransform = uc.NewTransformer().SetDescription("Second Transformer");
var bbb = SecondTransform.FromTo("Test {etc}.", "({etc})");

wl(aaa.@ParentTransformer().@Description())
wl(FirstTransform.Transform().@Text())
wl("")

wl(SecondTransform.@Description())
wl(bbb.@ParentTransformer().Transform(Txt).@Text())
```

**Output:**
```
First Transformer
[a b c] x y z

Second Transformer
(a b c) x y z
```

---

### Example ID: 134

**Description:** Replacement()

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("aaa bbb xyz 123");
var aaa = t.FromTo("aaa", "111");
var xyz = t.Pattern("xyz");
t.Filter();
wl(t.@Matches().@Text())

wl("-----")
wl(aaa.@Replacement())
wl(xyz.@Replacement())

```

**Output:**
```
111
xyz
-----
111
{@Self}
```

---

### Example ID: 137

**Description:** SkipOver(),  Str(), Implicit Str()

**Code:**
```pseudocode
var t = uc.NewTransformer();
var txt = "a b c (a b c a b c) a b c";
t.FromTo("a", "AA");

// You can either set the string before or pass it to Transform()
t.Str(txt);
wl(t.Transform().@Text())

t.SkipOver("({text})");
wl(t.Transform(txt)) // Implicit Text property
```

**Output:**
```
AA b c (AA b c AA b c) AA b c
AA b c (a b c a b c) AA b c
```

---

### Example ID: 138

**Description:** Rule StartAfter()

**Code:**
```pseudocode
var t = uc.NewTransformer();
var FruitsXML = 
[verbatim]
<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' />
  <Fruit CommonName='Strawberry' ScientificName='Fragaria × ananassa' />
  <Fruit CommonName='Pineapple' ScientificName='Ananas comosus' />
  <Fruit CommonName='Mango' ScientificName='Mangifera indica' />
  <Fruit CommonName='Blueberry' ScientificName='Vaccinium corymbosum' />
  <Fruit CommonName='Rambutan' ScientificName='Nephelium lappaceum' />
  <Fruit CommonName='Salak (Snake Fruit)' ScientificName='Salacca zalacca' />
  <Fruit CommonName='Jabuticaba' ScientificName='Plinia cauliflora' />
  <Fruit CommonName='Watermelon' ScientificName='Citrullus lanatus' />
</Fruits>
[/verbatim];

var Fruit = t.FromTo("CommonName={@string:name}", "{name}");

// StopAfter()
Fruit.@StopAfter(4);
t.Filter(FruitsXML);
wl("*** Stop after: ", Fruit.@StopAfter(), " ***")
wl(t.@Matches().@Text())
Fruit.@StopAfter(-1); // Resets back to infinity (default) for next example
wl("")

// StartAfter()
Fruit.@StartAfter(6);
t.Filter(FruitsXML);
wl("*** Start after: ", Fruit.@StartAfter(), " ***")
wl(t.@Matches().@Text())
Fruit.@StartAfter(0); // Resets back to 0 (default) for next example
wl("")


// Both StartAfter() and StopAfter()
Fruit.SetStartAfter(2).SetStopAfter(5);
t.Filter(FruitsXML);
wl("*** Between ", Fruit.@StartAfter() + 1, " and ", Fruit.@StopAfter(), " ***")
wl(t.@Matches().@Text())
wl("")

// All
uc.DefineVariable("x = 1");
Fruit = t.FromTo("CommonName={@string:name}", "{@Eval: x++}. {name}");
t.Filter(FruitsXML);
wl("*** All ***")
wl(t.@Matches().@Text())
```

**Output:**
```
*** Stop after: 4 ***
Apple
Banana
Orange
Grapes

*** Start after: 6 ***
Mango
Blueberry
Rambutan
Salak (Snake Fruit)
Jabuticaba
Watermelon

*** Between 3 and 5 ***
Orange
Grapes
Strawberry

*** All ***
1. Apple
2. Banana
3. Orange
4. Grapes
5. Strawberry
6. Pineapple
7. Mango
8. Blueberry
9. Rambutan
10. Salak (Snake Fruit)
11. Jabuticaba
12. Watermelon
```

---

### Example ID: 139

**Description:** Focusable to select only patterns from local transformer

**Code:**
```pseudocode
var t = uc.NewTransformer();
var FruitsXML =
[verbatim]
<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <!-- <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' /> -->
  <Fruit CommonName='Strawberry' ScientificName='Fragaria × ananassa' />
  <Fruit CommonName='Pineapple' ScientificName='Ananas comosus' />
  <!-- <Fruit CommonName='Mango' ScientificName='Mangifera indica' /> -->
  <Fruit CommonName='Blueberry' ScientificName='Vaccinium corymbosum' />
  <!-- <Fruit CommonName='Rambutan' ScientificName='Nephelium lappaceum' /> -->
  <Fruit CommonName='Salak (Snake Fruit)' ScientificName='Salacca zalacca' />
  <Fruit CommonName='Jabuticaba' ScientificName='Plinia cauliflora' />
  <!-- <Fruit CommonName='Watermelon' ScientificName='Citrullus lanatus' /> -->
</Fruits>
[/verbatim];

// List names of fruit within comment, not the whole comment as well
t.@Text(FruitsXML);
var CommentedFruits = t.Pattern("<!-- {comment} -->").SetFocusable(false);
var CommentedFruitsTr = CommentedFruits.@LocalTransformer();
CommentedFruitsTr.FromTo("CommonName={@string:text}", "{text}").@Focusable(true);

t.Filter();
wl("With Focusable()")
wl("----------------")
wl(t.GetMatches(MatchesOption::FocusableOnly).@Text())
wl("")

// Note: The displayed Fruit element is modified by CommentedFruitsTr.FromTo()
wl("Without Focusable()")
wl("-------------------")
wl(t.@Matches().@Text())
```

**Output:**
```
With Focusable()
----------------
Grapes
Mango
Rambutan
Watermelon

Without Focusable()
-------------------
<!-- <Fruit Grapes ScientificName='Vitis vinifera' /> -->
Grapes
<!-- <Fruit Mango ScientificName='Mangifera indica' /> -->
Mango
<!-- <Fruit Rambutan ScientificName='Nephelium lappaceum' /> -->
Rambutan
<!-- <Fruit Watermelon ScientificName='Citrullus lanatus' /> -->
Watermelon
```

---

### Example ID: 140

**Description:** StatementSensitive()

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("x = 1; if (true) func1(3+4); else func2(x*y); y = x + 2");
var p = t.Pattern("if {etc}");

wl("Input: ", t.@Text())
wl("Pattern: ", p.@Pattern())
wl("")

t.Find();
wl("StatementSensitive: ", bool(t.@DefaultRuleSet().@StatementSensitive()))
wl(t.@Matches().@Text())
wl("")

t.@DefaultRuleSet().@StatementSensitive(false);
t.Find();
wl("StatementSensitive: ", bool(t.@DefaultRuleSet().@StatementSensitive()))
wl(t.@Matches().@Text())
```

**Output:**
```
Input: x = 1; if (true) func1(3+4); else func2(x*y); y = x + 2
Pattern: if {etc}

StatementSensitive: True
if (true) func1(3+4)

StatementSensitive: False
if (true) func1(3+4); else func2(x*y); y = x + 2
```

---

### Example ID: 141

**Description:** Rule uCalc

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("The value is: x");

uc.DefineVariable("VarX");
t.FromTo("x", "{@Eval: VarX}").@uCalc().Eval("VarX = 123");

t.Transform();
wl(t.@Text())
```

**Output:**
```
The value is: 123
```

---

### Example ID: 142

**Description:** WhitespaceSensitive()

**Code:**
```pseudocode
var t = uc.NewTransformer();
var Text = "This is a test.";
var p = t.FromTo("This {words:3}", "[{words}]");

wl("Input: ", Text)
wl("Pattern: ", p.@Pattern())
wl("")

wl("3 captured tokens are in brackets")
wl("")

wl("WhitespaceSensitive = ", bool(t.@DefaultRuleSet().@WhitespaceSensitive()))
wl(t.Transform(Text))
wl("")

t.@DefaultRuleSet().@WhitespaceSensitive(true);
wl("WhitespaceSensitive = ", bool(t.@DefaultRuleSet().@WhitespaceSensitive()))
wl(t.Transform(Text))

```

**Output:**
```
Input: This is a test.
Pattern: This {words:3}

3 captured tokens are in brackets

WhitespaceSensitive = False
[is a test].

WhitespaceSensitive = True
[ is ]a test.
```

---

### Example ID: 143

**Description:** Minimum, GlobalMinimum

**Code:**
```pseudocode
var FruitsXML = 
[verbatim]
<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' />
  <Fruit CommonName='Strawberry' ScientificName='Fragaria × ananassa' />
  <Fruit CommonName='Pineapple' ScientificName='Ananas comosus' />
  <Fruit CommonName='Mango' ScientificName='Mangifera indica' />
  <Fruit CommonName='Blueberry' ScientificName='Vaccinium corymbosum' />
  <Fruit CommonName='Rambutan' ScientificName='Nephelium lappaceum' />
  <Fruit CommonName='Salak (Snake Fruit)' ScientificName='Salacca zalacca' />
  <Fruit CommonName='Jabuticaba' ScientificName='Plinia cauliflora' />
  <Fruit CommonName='Watermelon' ScientificName='Citrullus lanatus' />
</Fruits>
[/verbatim];

uc.DefineVariable("x = 1");
var t = uc.NewTransformer();
var FruitsTag = t.FromTo("<Fruits>", "List of fruits");
var Fruit = t.FromTo("CommonName={@string:name}", "{@Eval: x++}. {name}");

Fruit.@Minimum(20);
t.Filter(FruitsXML);
wl("Minimum = ", Fruit.@Minimum())
wl("Matches count: ", t.@Matches().Count()) // 1 for FruitsTag occurrence 
wl("")
wl(t.@Matches())
wl("")
wl("===============")

uc.Eval("x = 1");
Fruit.@Minimum(10);
t.Filter(FruitsXML);
wl("Minimum = ", Fruit.@Minimum())
wl("Matches count: ", t.@Matches().Count()) // 1 for FruitsTag plus 12 fruits
wl("")
wl(t.@Matches())
wl("")
wl("===============")

uc.Eval("x = 1");
Fruit.@GlobalMinimum(20); // Notice "List of fruits" will not show
t.Filter(FruitsXML);
wl("MinimumAND = ", Fruit.@GlobalMinimum())
wl("Matches count: ", t.@Matches().Count()) // Even FruitsTage won't be counted
wl("")
wl(t.@Matches())
wl("===============")

uc.Eval("x = 1");
Fruit.@GlobalMinimum(10);
t.Filter(FruitsXML);
wl("MinimumAND = ", Fruit.@GlobalMinimum())
wl("Matches count: ", t.@Matches().Count())
wl("")
wl(t.@Matches())

```

**Output:**
```
Minimum = 20
Matches count: 1

List of fruits

===============
Minimum = 10
Matches count: 13

List of fruits
1. Apple
2. Banana
3. Orange
4. Grapes
5. Strawberry
6. Pineapple
7. Mango
8. Blueberry
9. Rambutan
10. Salak (Snake Fruit)
11. Jabuticaba
12. Watermelon

===============
MinimumAND = 20
Matches count: 0


===============
MinimumAND = 10
Matches count: 13

List of fruits
1. Apple
2. Banana
3. Orange
4. Grapes
5. Strawberry
6. Pineapple
7. Mango
8. Blueberry
9. Rambutan
10. Salak (Snake Fruit)
11. Jabuticaba
12. Watermelon
```

---

### Example ID: 144

**Description:** QuoteSensitive

**Code:**
```pseudocode
var t = uc.NewTransformer().SetText("Test1 'a b c' a b c Test2 'a b c' a b c");

var Test1 = t.FromTo("Test1 {txt} b", "[{txt}]"); // defaults to QuoteSensitive = true
var Test2 = t.FromTo("Test2 {txt} b", "({txt})").SetQuoteSensitive(false);
t.Transform();

wl("Test1 QuoteSensitive = ", bool(Test1.@QuoteSensitive()))
wl("Test2 QuoteSensitive = ", bool(Test2.@QuoteSensitive()))

wl(t)
```

**Output:**
```
Test1 QuoteSensitive = True
Test2 QuoteSensitive = False
['a b c' a] c ('a) c' a b c
```

---

### Example ID: 145

**Description:** How to define and then permanently remove a rule.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var(string, text) = "(this and that) <this or that>";
t.@Text(text);

// Define two rules
var rule1 = t.FromTo("({txt})", "#{txt}#");
var rule2 = t.FromTo("<{txt}>", "${txt}$");

// Transform with both rules active
wl(t.Transform())

// Release the first rule
rule1.Release();

// Re-run the transformation; only the second rule applies
t.@Text(text);
wl(t.Transform())
```

**Output:**
```
#this and that# $this or that$
(this and that) $this or that$
```

---

### Example ID: 148

**Description:** MatchesOption: RootLevelOnly and InnermostOnly

**Code:**
```pseudocode
var t = uc.NewTransformer();
var txt = "<p id='aa'>xyz</p><p id='bb'>Hello</p ><p id='cc'>World</p>";
t.Str(txt);

t.Pattern("<p {etc}>").@LocalTransformer().FromTo("id={@string:id}", "{id}");
t.Filter();


wl("All matches")
wl("-----------")
wl(t.GetMatches(MatchesOption::All).@Text()) // All is the default
wl("")

wl("RootLevelOnly")
wl("-------------")
wl(t.GetMatches(MatchesOption::RootLevelOnly).@Text())
wl("")

wl("InnermostOnly")
wl("-------------")
wl(t.GetMatches(MatchesOption::InnermostOnly).@Text())
wl("")
```

**Output:**
```
All matches
-----------
<p aa>
aa
<p bb>
bb
<p cc>
cc

RootLevelOnly
-------------
<p aa>
<p bb>
<p cc>

InnermostOnly
-------------
aa
bb
cc
```

---

### Example ID: 149

**Description:** Pass()

**Code:**
```pseudocode
var FruitsXML = 
[verbatim]
<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' />
  <Fruit CommonName='Strawberry' ScientificName='Fragaria × ananassa' />
  <Fruit CommonName='Pineapple' ScientificName='Ananas comosus' />
  <Fruit CommonName='Mango' ScientificName='Mangifera indica' />
  <Fruit CommonName='Blueberry' ScientificName='Vaccinium corymbosum' />
  <Fruit CommonName='Rambutan' ScientificName='Nephelium lappaceum' />
  <Fruit CommonName='Salak (Snake Fruit)' ScientificName='Salacca zalacca' />
  <Fruit CommonName='Jabuticaba' ScientificName='Plinia cauliflora' />
  <Fruit CommonName='Watermelon' ScientificName='Citrullus lanatus' />
</Fruits>
[/verbatim];

var t = uc.NewTransformer();
t.@Text(FruitsXML);

var Pass1 = t.Pass();
var Pass2 = t.Pass();

Pass1.@Description("Pass A");
Pass1.FromTo("Fruits", "ListOfFruits");
Pass1.FromTo("<Fruit CommonName={@str:name} ScientificName={@str:sci_name} />", "<Fruit>{name}</Fruit>");

Pass2.@Description("Pass B");
Pass2.FromTo("{Fruit: Apple | Orange | Mango }", "{Fruit} *");
Pass2.FromTo("{Fruit: Banana | Grapes | Watermelon }", "{Fruit} **");

t.Transform();
wl("All passes")
wl("----------")
wl(t.@Text())

wl(t.Pass(0).@Description())
wl(t.Pass(1).@Description())
wl("Pass count: ", t.PassCount())
wl("")

t.Str(FruitsXML);
Pass2.Release();
t.Transform();
wl("Pass1 only (Pass2 released)")
wl("---------------------------")
wl(t.@Text())

```

**Output:**
```
All passes
----------

<ListOfFruits>
  <Fruit>Apple *</Fruit>
  <Fruit>Banana **</Fruit>
  <Fruit>Orange *</Fruit>
  <Fruit>Grapes **</Fruit>
  <Fruit>Strawberry</Fruit>
  <Fruit>Pineapple</Fruit>
  <Fruit>Mango *</Fruit>
  <Fruit>Blueberry</Fruit>
  <Fruit>Rambutan</Fruit>
  <Fruit>Salak (Snake Fruit)</Fruit>
  <Fruit>Jabuticaba</Fruit>
  <Fruit>Watermelon **</Fruit>
</ListOfFruits>

Pass A
Pass B
Pass count: 2

Pass1 only (Pass2 released)
---------------------------

<ListOfFruits>
  <Fruit>Apple</Fruit>
  <Fruit>Banana</Fruit>
  <Fruit>Orange</Fruit>
  <Fruit>Grapes</Fruit>
  <Fruit>Strawberry</Fruit>
  <Fruit>Pineapple</Fruit>
  <Fruit>Mango</Fruit>
  <Fruit>Blueberry</Fruit>
  <Fruit>Rambutan</Fruit>
  <Fruit>Salak (Snake Fruit)</Fruit>
  <Fruit>Jabuticaba</Fruit>
  <Fruit>Watermelon</Fruit>
</ListOfFruits>
```

---

### Example ID: 151

**Description:** Transformer Reset()

**Code:**
```pseudocode
var t = uc.NewTransformer();
var txt = "a b c d e";

t.@Text(txt);
t.FromTo("a", "aaa");
t.FromTo("c", "xyz");

wl("Input: ", t)
wl("Transformed: ", t.Transform())

wl("Reset")
t.Reset();

wl("Input: ", t, "(empty)")
t.@Text("a b c d e");
wl("New input: ", t.@Text())
wl("Transformed: ", t.Transform().@Text(), " (no transform)")
wl("New rules")

t.FromTo("b", "ABC");
t.FromTo("d", "DDD");
wl("Transformed: ", t.Transform().@Text())

```

**Output:**
```
Input: a b c d e
Transformed: aaa b xyz d e
Reset
Input: (empty)
New input: a b c d e
Transformed: a b c d e (no transform)
New rules
Transformed: a ABC c DDD e
```

---

### Example ID: 152

**Description:** RewindOnChange

**Code:**
```pseudocode
var ExprT = uc.@ExpressionTransformer();  // Transformer used for Eval() and Evaluate()

ExprT.@DefaultRuleSet().@RewindOnChange(true);

ExprT.FromTo("AddUp({x})", "{x}");
ExprT.FromTo("AddUp({x}, {y})", "({x} + AddUp({y}))");

ExprT.FromTo("ArgCount({x})", "1");
ExprT.FromTo("ArgCount({x}, {y})", "(1 + ArgCount({y}))");

ExprT.FromTo("Average({x}, {y})", "AddUp({x}, {y}) / ArgCount({x}, {y})");

var Expression = "Average(1, 2, 3, 4)";
wl("Input: ", Expression)
wl("Transform: ", ExprT.Transform(Expression))
wl("Eval: ", uc.Eval(Expression))
```

**Output:**
```
Input: Average(1, 2, 3, 4)
Transform: (1 + (2 + (3 + 4))) / (1 + (1 + (1 + 1)))
Eval: 2.5
```

---

### Example ID: 154

**Description:** To_uCalcString

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("if (x > 3) y = x * 2; else if(x == 5) y = x - 1;");
t.FromTo("1", "100");
t.Transform();

var Pattern = "if ({cond})";
wl([NotCpp]new [/NotCpp] uCalc::String(t).After(Pattern).@Text())
wl([NotCpp]new [/NotCpp] uCalc::String(t).After(Pattern).After(Pattern))

New(uCalc::String, s)
s = "This is a test";
wl([NotCpp]new [/NotCpp] uCalc::Transformer(s).@Text())
```

**Output:**
```
y = x * 2; else if(x == 5) y = x - 100;
 y = x - 100;
This is a test
```

---

### Example ID: 155

**Description:** Transformer: Matching by tokens vs match by character; also whitespace sensitivity

**Code:**
```pseudocode
// This examples shows the default match by
// token mode, as well as how to reconfigure
// it in order to do match by character
// along with a whitespace variation

var t = uc.NewTransformer();
var txt = "This is an island test, I said.";
t.FromTo("is", "<is>");

wl(t.Transform(txt))
wl("")

t.@Tokens().@Description("Match by character");
t.@Tokens().Add("."); // This overrides existing tokens
t.FromTo("is", "<is>");
wl(t.@Tokens().@Description())
wl(t.Transform(txt))
wl("")

// Note: whitespace sensitivity is off by default
// Whitespace token is re-introduced
// (after being overridden in the previous Token Add())
t.@Tokens().@Description("By char + whitespace ignored");
t.@Tokens().Add("[\\t\\v ]+", TokenType::Whitespace);
t.FromTo("is", "<{@Self}>");
wl(t.@Tokens().@Description())
wl(t.Transform(txt))
```

**Output:**
```
This <is> an island test, I said.

Match by character
Th<is> <is> an <is>land test, I said.

By char + whitespace ignored
Th<is> <is> an <is>land test, <I s>aid.
```

---

### Example ID: 156

**Description:** Implicit Str(), Transform()

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("a", "XY");

t.@Text("a b c a b c");
wl(t.Transform().@Text()) // Text that was set before trasnform
wl(t.Transform("c b a c b a").@Text()) // text passed to Transform()
wl(t.Transform("a, b, a, b")) // Implicit; Text property can be omitted
```

**Output:**
```
XY b c XY b c
c b XY c b XY
XY, b, XY, b
```

---

### Example ID: 157

**Description:** StrLength()

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("a b c d e f");
t.FromTo("{ a | d }", "xy");

wl(t)
wl("Length: ", t.StrLength())
wl("")
wl(t.Transform())
wl("Length: ", t.StrLength())
```

**Output:**
```
a b c d e f
Length: 11

xy b c xy e f
Length: 13
```

---

### Example ID: 158

**Description:** Transformer.uCalc

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@uCalc().DefineVariable("xyz = 123");

t.FromTo("xyz", "{@Eval: xyz * 10}");
wl(t.Transform("The answer is: xyz"))
```

**Output:**
```
The answer is: 1230
```

---

### Example ID: 159

**Description:** WasModified

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("a", "*a good*");

t.@Text("This is a test");
wl(t.Transform())
wl("Modified: ", bool(t.@WasModified()))
wl("")

t.@Text("This is another test");
wl(t.Transform())
wl("Modified: ", bool(t.@WasModified()))
```

**Output:**
```
This is *a good* test
Modified: True

This is another test
Modified: False
```

---

### Example ID: 160

**Description:** Changing the parent uCalc object for a Transformer

**Code:**
```pseudocode
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)}";

new(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}");
wl(t.Transform(text))

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

```

**Output:**
```
Adding 1 and 2 gives: 3. f(5) = 50
Adding 111 and 222 gives: 333. f(5) = 5000
```

---

### Example ID: 161

**Description:** "using" (C#) and Owned (C++) for auto-releasing uCalc object

**Code:**
```pseudocode

// In C# and VB you should use "using".
// In C++ you can flag a uCalc object for
// auto-release with Owned(), or by setting
// the last parameter of the constructor to true.

uc.@IsDefault(true); // Set uc as the default uCalc object
uCalc::@DefaultInstance().DefineVariable("Value = 'Original uc object'");
wl(uCalc::@DefaultInstance().EvalStr("Value")) // Outputs: Original uc object

[NotCpp]// Use "using" so that the object is auto-released when it it goes out of scope[/NotCpp]
   NewUsing(uCalc, uCalcTemp) [cpp]// Make uCalcTemp owned so it reverts back to uc when uCalcTemp goes out of scope[/cpp]
   uCalcTemp.@IsDefault(true); // Set uCalcTemp as the default uCalc object
   uCalc::@DefaultInstance().DefineVariable("Value = 'uCalcTemp object'");
   wl(uCalc::@DefaultInstance().EvalStr("Value")) // uCalcTemp object
End Using
// uCalcTemp goes out of scope here, and the default uCalc object reverts back to uc

wl(uCalc::@DefaultInstance().EvalStr("Value")) // Original uc object

[c]{!Eval: Chr(123)}[/c][vb]If True Then[/vb]
   [cs]/*using*/[/cs] New(uCalc, uCalcSticky) // remains the default even after going out of scope
   uCalcSticky.@IsDefault(true); // Set uCalcSticky as the default uCalc object
   uCalc::@DefaultInstance().DefineVariable("Value = 'uCalcSticky object'");
   wl(uCalc::@DefaultInstance().EvalStr("Value")) // Outputs: uCalcSticky object
[c]{!Eval: Chr(125)}[/c][vb]End If[/vb]    // The uCalcSticky object itself goes out of scope here, but internally it remains the default uCalc object

wl(uCalc::@DefaultInstance().EvalStr("Value"))
```

**Output:**
```
Original uc object
uCalcTemp object
Original uc object
uCalcSticky object
uCalcSticky object
```

---

### Example ID: 162

**Description:** "using" (C#) and Owned (C++) for auto-releasing Transformer object

**Code:**
```pseudocode

// In C# and VB you should use "using".
// In C++ you can flag a uCalc object for
// auto-release with Owned(), or by setting
// the last parameter of the constructor to true.

New(uCalc::Transformer, t(uc))
var MemIndex = t.@MemoryIndex();
t.Release(); // MemIndex will be recycled and assigned to the next def

[NotCpp]// Use "using" so that the object is auto-released when it it goes out of scope[/NotCpp]
   NewUsing(uCalc::Transformer, TempTransform(uc)) [cpp]// Owned() causes TempTransform to be released when it goes out of scope[/cpp]
   wl(bool(TempTransform.@MemoryIndex() == MemIndex)) // MemoryIndex() will be the recycled value of the released t object
End Using
// TempTransform goes out of scope here

New(uCalc::Transformer, t3(uc))
wl(bool(t3.@MemoryIndex() == MemIndex)) // MemoryIndex() will be the recycled value of the released TempTransform object
t3.Release();

[c]{!Eval: Chr(123)}[/c][vb]If True Then[/vb][NotCpp]
   // Use "using" so that the object is auto-released when it it goes out of scope[/NotCpp]
   New(uCalc::Transformer, StickyTransformer(uc)) [cpp]// StickyTransformer here does NOT get released when it goes out of scope[/cpp]
   wl(bool(StickyTransformer.@MemoryIndex() == MemIndex))
[c]{!Eval: Chr(125)}[/c][vb]End If[/vb] // StickyTransformer remains in memery

New(uCalc::Transformer, t4(uc))
wl(bool(t4.@MemoryIndex() == MemIndex)) // False since StickyTransformer was not released; MemoryIndex() has a new value
```

**Output:**
```
True
True
True
False
```

---

### Example ID: 163

**Description:** Token Add(ExistingToken)

**Code:**
```pseudocode

var t1 = uc.NewTransformer();
var CommentRegex = [verbatim]/\*([\s\S]*?)\*/[/verbatim];
var WhitespaceToken = t1.@Tokens().Add(CommentRegex, TokenType::Whitespace);
WhitespaceToken.@Description("Treats text between /* and */ as whitespace");

var txt = "a b, a /* comment a b */ b, a x b, ab, a   b, a, b";

var t2 = uc.NewTransformer();
t2.FromTo("a b", "<{@Self}>");
t2.Transform(txt);
wl(t2)

// The token defined in the other transformer (WhitespaceToken) is imported into this one.
// Now, everything between /* and */ will be treated as whitespace
t2.@Tokens().Add(WhitespaceToken);
wl(t2.Transform(txt))
```

**Output:**
```
<a b>, a /* comment <a b> */ b, a x b, ab, <a   b>, a, b
<a b>, <a /* comment a b */ b>, a x b, ab, <a   b>, a, b
```

---

### Example ID: 165

**Description:** Defining a token bracket pair

**Code:**
```pseudocode

// Here we define < and > as a bracket pair.
// Such pairs can be part of a pattern match
// and a match can be found within a bracket pair
// but a match will not cross boundaries with one
// part of the match out and another part inside

var t = uc.NewTransformer();
var txt = "a < b c > c, < a > b c, < a b c >";

t.@Tokens().Add("<", TokenType::Generic, ">");
t.FromTo("a {etc} c", "((a {etc} c))");

wl(txt)
wl(t.Transform(txt))
```

**Output:**
```
a < b c > c, < a > b c, < a b c >
((a < b c > c)), < a > b c, < ((a b c)) >
```

---

### Example ID: 166

**Description:** Defining quoted text 

**Code:**
```pseudocode

// In example we'll define quoted text using < and > as
// surrounding quotes.  Singe and double quotes ' and " 
// are already defined by default.  This is just an example.

// Quoted text must be defined as TokenType.Literal
// The last argument, 1, means that the literal part of the match will
// be the part of the regex found int the first parenthesis (here's
// there's only one set of parenthesis).

var t = uc.NewTransformer();
var SpecialQuotes = t.@Tokens().Add("<([^>]*)>", TokenType::Literal, "", 1);
SpecialQuotes.SetDataType(BuiltInType::String);
SpecialQuotes.IsProperty(ItemIs::QuotedText, true);

t.Pattern("{token:1}");
wl(t.Filter("abc <some quoted text> xyz 123.456 + 25e2").@Matches().@Text())
wl("")

// Based on the definition, the part within < and > is the literal part
// passed to the string + operator used by EvalStr

uc.@ExpressionTokens().Add(SpecialQuotes);
wl(uc.EvalStr("<some quoted text> + < plus more>"));
```

**Output:**
```
abc
<some quoted text>
xyz
123.456
+
25e2

some quoted text plus more
```

---

### Example ID: 167

**Description:** Importing a list of tokens from one transformer to another

**Code:**
```pseudocode
var t = uc.NewTransformer();

// This creates a simpler (not very useful) set of tokens for sake of example
var MyTokens = t.@Tokens();
MyTokens.Clear(); // removes the default list of tokens
MyTokens.Add("."); // Should always have a fallback token like this one
MyTokens.Add(";", TokenType::StatementSep);
MyTokens.Add("<", TokenType::Generic, ">");
MyTokens.Add("[0-9]+", TokenType::Literal);
MyTokens.Add(" +", TokenType::Whitespace);
MyTokens.Add("[a-z]+", TokenType::AlphaNumeric);

t.FromTo("{ This | That} {etc}", "[{@Self}]"); // {etc} stops at the semicolon ";" TokenType.StatementSep

wl(t.Transform("This is a test; That < 123.456; abc >; ABC"))
wl("")

New(uCalc::Transformer, OtherTransform(uc)) // This is an alternative way of constructing a new transformer
OtherTransform.@Tokens().Add(MyTokens); // Imports the entire token list from the other transformer
OtherTransform.Pattern("{word:1}");

wl(OtherTransform.Filter("This is a test; That < 123.456; abc >; ABC").@Matches().@Text())

```

**Output:**
```
[This is a test]; [That < 123.456; abc >]; ABC

This
is
a
test
;
That
<
123
.
456
;
abc
>
;
ABC
```

---

### Example ID: 168

**Description:** Token Context switch

**Code:**
```pseudocode
var CommentTransform = uc.NewTransformer();
var CommentTokens = CommentTransform.@Tokens();
CommentTokens.Add(".");
CommentTokens.Add("[a-z]+");

var txt = "'This is it' /* 'This is it' This is it */ This is it";

var t = uc.NewTransformer();
t.FromTo("is", "<is>");
wl(t.Transform(txt).@Text())

// Now the context will switch between /* and */
// In that context there's no quoted text token,
t.@Tokens().ContextSwitch(CommentTokens, [c]"/\\*"[/c][vb]"/\*"[/vb], [c]"\\*/"[/c][vb]"\*/"[/vb]);
t.FromTo("is", "<is>");
wl(t.Transform(txt).@Text())

```

**Output:**
```
'This is it' /* 'This is it' This <is> it */ This <is> it
'This is it' /* 'This <is> it' This <is> it */ This <is> it
```

---

### Example ID: 169

**Description:** Token Remove

**Code:**
```pseudocode
// This example removes the single quote pattern from the list

var t = uc.NewTransformer();
var txt = "This is a test, 'This is a test'";
t.FromTo("{token:1}", "<{@Self}>");
wl(t.Transform(txt).@Text())

// Now the ' character will no longer be special
// (see the Name() example for list of token names
t.@Tokens().Remove(t.@Tokens()["_token_string_singlequoted"]);
wl(t.Transform(txt).@Text())
```

**Output:**
```
<This> <is> <a> <test><,> <'This is a test'>
<This> <is> <a> <test><,> <'><This> <is> <a> <test><'>
```

---

### Example ID: 170

**Description:** Token(TokenType)

**Code:**
```pseudocode
wl(uc.@ExpressionTokens()[TokenType::AlphaNumeric].@Name())
wl(uc.@ExpressionTokens()[TokenType::AlphaNumeric].@Regex())
wl("")

// Note: In C# or VB you can simply use [TokenType::Literal, n]
// instead of ByType(TokenType::Literal, n)
wl(uc.@ExpressionTokens().ByType(TokenType::Literal, 0).@Name())
wl(uc.@ExpressionTokens().ByType(TokenType::Literal, 1).@Name())
wl(uc.@ExpressionTokens().ByType(TokenType::Literal, 2).@Name())
```

**Output:**
```
_token_alphanumeric
[a-zA-Z_][a-zA-Z0-9_]*

_token_string_singlequoted
_token_string_doublequoted
_token_string_tripledoublequoted
```

---

### Example ID: 171

**Description:** uCalc Description

**Code:**
```pseudocode
uc.@Description("This is the main uCalc object");
var t = uc.NewTransformer();
wl(t.@Tokens().@uCalc().@Description())
```

**Output:**
```
This is the main uCalc object
```

---

### Example ID: 173

**Description:** Pattern: Simple Variable Capture

**Code:**
```pseudocode
var t = uc.NewTransformer();
t = "Here is the temperature: 98.6 F";

// Define the pattern first
t.Pattern("Temperature: {temp} F");

// Then execute the search
t.Find();

wl(t.@Matches()[0][cpp].@Text()[/cpp])
```

**Output:**
```
temperature: 98.6 F
```

---

### Example ID: 174

**Description:** Converting from Celsius to Fahrenheit with the Transformer

**Code:**
```pseudocode
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
wl(t.Transform("Here is the temperature: 22.5 C"))
```

**Output:**
```
Here is the temperature: 72.5 F
```

---

### Example ID: 175

**Description:** Turn new line into whitespace with Tokens.Add

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("<{tag}>{code}</{tag}>", "[{tag}]{code}[/{tag}]");
var MyStr = [verbatim]<div>Single line</div>
<div>Line 1
Line 2
Line 3
Line 4</div>[/verbatim];

wl("New line as statement separator (default)")
wl("")
wl(t.Transform(MyStr).@Text())
wl("")

wl("New line as whitespace")
wl("")
t.@Tokens().Add([c]"[\\r\\n]+"[/c][vb]"[\r\n]+"[/vb], TokenType::Whitespace);
wl(t.Transform(MyStr).@Text())



```

**Output:**
```
New line as statement separator (default)

[div]Single line[/div]
<div>Line 1
Line 2
Line 3
Line 4</div>

New line as whitespace

[div]Single line[/div]
[div]Line 1
Line 2
Line 3
Line 4[/div]
```

---

### Example ID: 176

**Description:** Matching by token type

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("{@String:txt}", "<<InnerQuote={txt}><TxtWithQuotes={txt(0)}>>");
t.FromTo("{@Number:MyNum}", "<NumericValue={MyNum}>");
t.FromTo("{@Bracket:MyBrack}", "<Brack={MyBrack}>");
t.FromTo("{@CloseBracket:CloseBr}", "<CloseBrack={CloseBr}>");
t.FromTo("{@StatementSeparator:Sep}", "<Separator={Sep}>");
t.FromTo("{@Alphanumeric:alpha}", "<Alpha={alpha}>");
t.FromTo("{@Whitespace:ws}", "<whitespace count={@Eval: Length(ws)}>");
t.FromTo("{@Reducible:r}", "<Reducible={r}>");
t.FromTo("{@Newline}", "<New line{@Newline}>");

var s = [verbatim]This is   55.2*6 "Hello world";
'Single quote'(parenth)[/verbatim];

wl(t.Filter(s).@Matches().@Text())
```

**Output:**
```
<Alpha=This>
<whitespace count=1>
<Alpha=is>
<whitespace count=3>
<NumericValue=55.2>
<Reducible=*>
<NumericValue=6>
<whitespace count=1>
<<InnerQuote=Hello world><TxtWithQuotes="Hello world">>
<Separator=;>
<New line
>
<<InnerQuote=Single quote><TxtWithQuotes='Single quote'>>
<Brack=(>
<Alpha=parenth>
<CloseBrack=)>
```

---

### Example ID: 177

**Description:** {@Alphanumeric}

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("({@Alphanumeric:txt})", "<Alpha str={txt}>");

wl(t.Transform("Testing 123 (456) (abc) ('text') (xyz111)"))
```

**Output:**
```
Testing 123 (456) <Alpha str=abc> ('text') <Alpha str=xyz111>
```

---

### Example ID: 178

**Description:** TypeOfToken

**Code:**
```pseudocode
// See uCalc.Tokens.Count() example for list of token names

var t = uc.NewTransformer();
var MyToken = t.@Tokens().Add("###");
var Alpha = t.@Tokens()["_token_alphanumeric"];

wl(bool(MyToken.@TypeOfToken() == TokenType::AlphaNumeric))
wl(bool(MyToken.@TypeOfToken() == TokenType::Generic))
wl(bool(Alpha.@TypeOfToken() == TokenType::AlphaNumeric))
wl(bool(Alpha.@TypeOfToken() == TokenType::Generic))


```

**Output:**
```
False
True
True
False
```

---

### Example ID: 179

**Description:** {@Whitespace}

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("{@Whitespace}", ",");

wl(t.Transform("This is   a 'small test' about ' whitespace ' tokens."))
```

**Output:**
```
This,is,a,'small test',about,' whitespace ',tokens.
```

---

### Example ID: 184

**Description:** {@StatementSeparator}

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("{@StatementSeparator}", "<sep>");
wl(t.Transform("a = b + c; x = y + 1;"))
```

**Output:**
```
a = b + c<sep> x = y + 1<sep>
```

---

### Example ID: 185

**Description:** {@Token} - matching a token by name

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("{@String}", "<Any quoted {@Self}>");
t.FromTo("({@Token(String_Singlequoted)})", "<Single quoted {@Self}>");
t.FromTo("({@Token(String_Doublequoted)})", "<Double quoted {@Self}>");

var s = [verbatim]"Test" '123' ("abc") ('xyz')[/verbatim];
wl(t.Transform(s))
```

**Output:**
```
<Any quoted "Test"> <Any quoted '123'> <Double quoted ("abc")> <Single quoted ('xyz')>
```

---

### Example ID: 187

**Description:** RulePatternTransformer

**Code:**
```pseudocode
var t = uc.NewTransformer();

var Pattern = uc.@TransformerForRulePatterns();
var Replacement = uc.@TransformerForRuleReplacements();

Pattern.FromTo("@sq", "{@Eval: '{@Token(_Token_String_SingleQuoted)}'}");
Replacement.FromTo("~", "{@Eval: '{@Self}'}");

t.FromTo("@sq", "<single quote txt = ~>");
// Same as t.FromTo("{@Token(_Token_QuoteChar_Single)}", "<single quote txt = {@Self}>"); 

wl(t.Transform("Test: 'some text'."))




```

**Output:**
```
Test: <single quote txt = 'some text'>.
```

---

### Example ID: 188

**Description:** Transformer constructor

**Code:**
```pseudocode
wl("Transformer constructors")
New(uCalc::Transformer, t1) // New transformer in default uCalc space
New(uCalc::Transformer, t2(uc)) // New transformer inherits
New(uCalc::Transformer, t3(t1.@Tokens())) // Imports tokens from t1
```

**Output:**
```
Transformer constructors
```

---

### Example ID: 189

**Description:** Whitespace

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("Hello World", "<{@Self}>");
wl(t.Transform("Hello World. HelloWorld. Hello     World. Hello, World."))
```

**Output:**
```
<Hello World>. HelloWorld. <Hello     World>. Hello, World.
```

---

### Example ID: 190

**Description:** Searching for two different words in parallel.

**Code:**
```pseudocode
var t = uc.NewTransformer();

// Define concurrent patterns
t.FromTo("Mango", "[Fruit]");
t.FromTo("Car", "[Vehicle]");

wl(t.Transform("I have a Mango and a Car.")) 

```

**Output:**
```
I have a [Fruit] and a [Vehicle].
```

---

### Example ID: 191

**Description:** More concurrent patterns

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.Pattern("This {etc} a");
t.Pattern("{@String}");
t.Pattern("{ big | small }");
t.Pattern("Only {words:2}");

wl(t.Filter("This is just a small Test to see 'how' patterns work. Only a test!").@Matches().@Text())
```

**Output:**
```
This is just a
small
'how'
Only a test
```

---

### Example ID: 192

**Description:** Order of concurrent patterns

**Code:**
```pseudocode
var t = uc.NewTransformer();

// Note: Since the patterns start the same,
//       the order in which they're defined matters.
t.FromTo("An {item}", "<{@Self}>");
t.FromTo("An {item}.", "[{@Self}]");
t.FromTo("An {item:2}.", "({@Self})");
t.FromTo("An orange.", "{{@Self}}");

wl(t.Transform("An apple. An orange. An elephant."))
wl(t.Transform("An angry bear. An extremely big dog!"))
```

**Output:**
```
[An apple.] {An orange.} [An elephant.]
(An angry bear.) <An extremely big dog!>
```

---

### Example ID: 193

**Description:** Variables and anchors

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("is {etc} see", "({@Self})");
wl(t.Transform("This is a test to see how anchors/variables work"))
```

**Output:**
```
This (is a test to see) how anchors/variables work
```

---

### Example ID: 194

**Description:** More on variables and anchors

**Code:**
```pseudocode
var t = uc.NewTransformer();

// Variables are {etc} and {ch}
// Anchors are "This", either "a small" or "an easy", and "Test"

t.FromTo("This {etc} {ch: a small | an easy } Test", "<{etc}> ({ch}) experiment");
wl(t.Transform("This is such an easy test."))
```

**Output:**
```
<is such> (an easy) experiment.
```

---

### Example ID: 195

**Description:** Named optional part

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("a [{option: small | big }] test",
         "a sample test{option: categorized as '{option}'}");

wl(t.Transform("This is a test."))
wl(t.Transform("This is a big test."))
wl(t.Transform("This is a small test."))
wl(t.Transform("This is a random test."))
```

**Output:**
```
This is a sample test.
This is a sample test categorized as 'big'.
This is a sample test categorized as 'small'.
This is a random test.
```

---

### Example ID: 196

**Description:** Alternative parts

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("This is a {adjective: simple | small | nice } test",
         "The adjective in '{@Self}' is: {adjective}.");

wl(t.Transform("This is a test"))
wl(t.Transform("This is a simple test"))
wl(t.Transform("This is a small test"))
wl(t.Transform("This is a nice test"))
wl(t.Transform("This is a random test"))

```

**Output:**
```
This is a test
The adjective in 'This is a simple test' is: simple.
The adjective in 'This is a small test' is: small.
The adjective in 'This is a nice test' is: nice.
This is a random test
```

---

### Example ID: 197

**Description:** Optional part

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("a [simple] test", "<{@Self}>");

wl(t.Transform("Is this a simple test, or a hard test, or just a test?"))
```

**Output:**
```
Is this <a simple test>, or a hard test, or just <a test>?
```

---

### Example ID: 198

**Description:** Optional part; value when optional part not used

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("This is a [{adj: simple}] test",
         "Let's take the {adj}{!adj:short} test");

wl(t.Transform("This is a test"))
wl(t.Transform("This is a simple test"))
```

**Output:**
```
Let's take the short test
Let's take the simple test
```

---

### Example ID: 199

**Description:** Using the same pattern variable multiple times in a pattern

**Code:**
```pseudocode
var t = uc.NewTransformer();

// When a variable is used multiple times in a pattern,
// such as {tag} in this case, the matching text must be the same

t.FromTo("<{tag}> {words:2} {more} </{tag}>",
"tag={tag}, 2 words={words}, text={more}");

wl(t.Transform("<div>abc xyz more words<b>bold</b></div>").@Text())
```

**Output:**
```
tag=div, 2 words=abc xyz, text=more words<b>bold</b>
```

---

### Example ID: 200

**Description:** Matching a certain number of tokens

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("is {TokenCount:4}", "is <{TokenCount}>");
wl("This example captures 4 tokens")
wl(t.Transform("This is just a small token match test"))

// Quoted text counts as one token
wl(t.Transform("This is a 'really really' small test with quoted text"))
```

**Output:**
```
This example captures 4 tokens
This is <just a small token> match test
This is <a 'really really' small test> with quoted text
```

---

### Example ID: 201

**Description:** {@Eval}, {@@Eval}, and escaping special characters in a pattern

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("'['{word}']'", "{@Eval: UCase(word)}");
t.FromTo("'{'{expr}'}'", "{@@Eval: expr}");

wl(t.Transform("Words like [this] and [that]."))
wl(t.Transform("Is {5*3} bigger than {5^3}?"))
```

**Output:**
```
Words like THIS and THAT.
Is 15 bigger than 125?
```

---

### Example ID: 202

**Description:** Transforming numeric ASCII codes to text characters

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("{#97#98#99}", "{#120#121#122}");
// Same as t.FromTo("abc", "xyz")

wl(t.Transform("abc"))
```

**Output:**
```
xyz
```

---

### Example ID: 203

**Description:** {@All}

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("{@All}", "<<{@Self}>>");

wl(t.Transform("This is a test"))
```

**Output:**
```
<<This is a test>>
```

---

### Example ID: 205

**Description:** {@Comment}

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("a {@Comment: Ignore this} b c", "x{@Comment: ignore} y z");

wl(t.Transform("a b. a b c. abc."))
```

**Output:**
```
a b. x y z. abc.
```

---

### Example ID: 206

**Description:** {@Define}

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.Pattern("{@Define: Var: xyz = 123}");
t.FromTo("abc", "{@Eval: xyz * 10}");
wl(t.Transform("The value is: abc"))

```

**Output:**
```
The value is: 1230
```

---

### Example ID: 207

**Description:** {@Doc}

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("a test", "'{@Self}' is part of: '{@Doc}'");

// Note: .Str(0) here is a shortcut for .Matches().Str(0)
wl(t.Transform("This sentence is just a test").Str(0))
```

**Output:**
```
'a test' is part of: 'This sentence is just a test'
```

---

### Example ID: 208

**Description:** {@Param}

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("This {etc} big test {words:2}",
         "{@Param:0}:{@Param:1}:{@Param:1+1}:{@Param:2+1}:{@Param:2*2}");
wl(t.Transform("This is a big test we have today"))
```

**Output:**
```
This:is a:big:test:we have today
```

---

### Example ID: 209

**Description:** {@Stop}

**Code:**
```pseudocode
var t = uc.NewTransformer();

// without {@Stop} "end" wouldn't be a match
t.FromTo("StopAt {abc} {@Stop} end", "<{abc}>");
t.FromTo("end", "[The End]");

wl(t.Transform("StopAt a b c end"))

```

**Output:**
```
<a b c> [The End]
```

---

### Example ID: 210

**Description:** Ignore quote directive `

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("a {txt} c", "<{@Self}>"); // Quoted text treated as 1 token
t.FromTo("x {txt`} z", "<{@Self}>"); // Quotes treated as ordinary chars

wl(t.Transform("a 'b c' b c :: x 'y z' y z"))
```

**Output:**
```
<a 'b c' b c> :: <x 'y z>' y z
```

---

### Example ID: 212

**Description:** Ignore bracket directive ^

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("begin {body} end",   "bracket not ignored: <{@Self}>");
t.FromTo("begin_ {body^} end", "bracket ignored:     <{@Self}>");

wl(t.Transform("begin (a b c end) end"))
wl(t.Transform("begin_ (a b c end) end"))
```

**Output:**
```
bracket not ignored: <begin (a b c end) end>
bracket ignored:     <begin_ (a b c end>) end
```

---

### Example ID: 213

**Description:** Pattern directive to skip nested pattern matching

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("start {etc} end", "<{@Self}>");
t.FromTo("start2 {etc~} end", "<{@Self}>");

wl(t.Transform("start start2 a b c end end"))
wl(t.Transform("start2 start a b c end end"))
```

**Output:**
```
<start start2 a b c end end>
<start2 start a b c end> end
```

---

### Example ID: 214

**Description:** TransformArg directive

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("abc", "changed to xyz");
t.FromTo("Quote1({arg})", "'{arg}'");
t.FromTo("Quote2({arg%})", "'{arg}'");

wl(t.Transform("Quote1(abc), Quote2(abc)"))

```

**Output:**
```
'abc', 'changed to xyz'
```

---

### Example ID: 215

**Description:** WhitespaceCounts

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("A {txtA}. B {txtB$}.", "<{txtA}> <{txtB}>");

wl(t.Transform("A     x y z . B     x y z ."))
```

**Output:**
```
<x y z> <     x y z >
```

---

### Example ID: 216

**Description:** {@Exec}

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.Pattern("{@Define: Var: Count_a = 0}");
t.Pattern("{@Define: Var: Count_an = 0}");

t.FromTo("a", "{@Self}{@Exec: Count_a++}");
t.FromTo("an", "{@Self}{@Exec: Count_an++}");
t.FromTo(".", [verbatim]{@nl}'a' occurs {@Eval: Count_a} times
'an' occurs {@Eval: Count_an} times[/verbatim]);

// Note: it is counting "a" as a token, not as a character.
wl(t.Transform("An apple, an eagle, a cat, an orange, a tree."))
```

**Output:**
```
An apple, an eagle, a cat, an orange, a tree
'a' occurs 2 times
'an' occurs 3 times
```

---

### Example ID: 217

**Description:** IgnoreStatementSeparator +

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("a {txt} c", "<{@Self}>"); 
t.FromTo("x {txt+} z", "<{@Self}>");

wl(t.Transform("a b c; :: x y z; :: a b; c :: x y; z"))
```

**Output:**
```
<a b c>; :: <x y z>; :: a b; c :: <x y; z>
```

---

### Example ID: 218

**Description:** Test: Complex Nesting & Backreferences

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("Start A ( 1 2 3 ) End A ... Start B ( 9 ) End B");

// {id} captures "A". {content} captures the block.
// The final {id} MUST match the first {id} ("A" == "A").
// If the text was "Start A ... End B", this pattern would NOT match.
t.Pattern("Start {id} ( {content} ) End {id:1}");

// +++ w/o 1 in {id:1} it tries to capture more than one token at
// position.  Investigate if it should logically be possible without 1

t.Find();
wl("Matches: ", t.@Matches().Count())
wl(t.@Matches().@Text())
```

**Output:**
```
Matches: 2
Start A ( 1 2 3 ) End A
Start B ( 9 ) End B
```

---

### Example ID: 219

**Description:** Test: Complex Nesting & Backreferences using XML-style tags.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<section> <item> A </item> </section>");

// {tag} captures "section". {content} captures the inner content.
// The closing </{tag}> MUST match the opening <{tag}>.
t.Pattern("<{tag}> {content} </{tag}>");

wl(t.Find().@Matches().@Text())
// This will match the outer <section> block.
// If the text was "<section> ... </div >", it would NOT match.

wl("-----")
t.Str([verbatim]
<br><section> <item> A </item> </section>
<br><br><div> <item> A b c </item> </div>
<br> <div> <item> <div>x y z</div> </item> </div>
[/verbatim]);
wl(t.Find().@Matches().@Text())
```

**Output:**
```
<section> <item> A </item> </section>
-----
<section> <item> A </item> </section>
<div> <item> A b c </item> </div>
<div> <item> <div>x y z</div> </item> </div>
```

---

### Example ID: 220

**Description:** Change newline from statement separator to whitespace

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.Str([verbatim]
<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div>
[/verbatim]);

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

wl("Newline as statement separator (default)")
wl("----------------------------------------")
wl(t.Find().@Matches().@Text())
wl("")

wl("Newline as whitespace")
wl("---------------------")
t.@Tokens()["_token_newline"].@TypeOfToken(TokenType::Whitespace);
wl(t.Find().@Matches().@Text())
```

**Output:**
```
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>
```

---

### Example ID: 221

**Description:** Change newline from statement separator to whitespace using TypeOfToken

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.Str([verbatim]
<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div>
[/verbatim]);

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

wl("Newline as statement separator (default)")
wl("----------------------------------------")
wl(t.Find().@Matches().@Text())
wl("")

wl("Newline as whitespace")
wl("---------------------")
NewLineToken.@TypeOfToken(TokenType::Whitespace);
wl(t.Find().@Matches().@Text())
```

**Output:**
```
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>
```

---

### Example ID: 223

**Description:** Using {@Whitespace} and {@Exec} to Count Indentation (for Python or YAML-like text)

**Code:**
```pseudocode
// Using {@Whitespace} to Count Indentation
// A common use case for parsing structured text (like Python or YAML)
// is capturing the exact whitespace at the start of a line.

uc.DefineVariable("IndentLen");

var t = uc.NewTransformer();
t.@Text("    Item 1"); // Indented by 4 spaces

// Capture the leading whitespace into 'w' and evaluate its length
t.FromTo("{@Whitespace:w} Item {id}", "<{@Self}>{@Exec: IndentLen = Length(w)}");
t.Transform();
// We can now analyze the captured whitespace
wl("Indentation length: ", uc.EvalStr("IndentLen"))
```

**Output:**
```
Indentation length: 4
```

---

### Example ID: 224

**Description:** A simple "Hello World" transformation demonstrating variable capture.

**Code:**
```pseudocode
var t = uc.NewTransformer();

// Define a rule to swap the name into a greeting
t.FromTo("Hello {name}", "Greetings, {name}!");
wl(t.Transform("Hello World"))
```

**Output:**
```
Greetings, World!
```

---

### Example ID: 227

**Description:** Demonstrating in-place modification with uCalc.String.Replace

**Code:**
```pseudocode
var(uCalc::String, text) = "This is foo 1, foo 2, Foo 3, foo 4";
text.After("1").Before("3").Replace("foo", "bar"); // 'text' is now modified
wl(text)
```

**Output:**
```
This is foo 1, bar 2, bar 3, foo 4
```

---

### Example ID: 228

**Description:** A simple Lexer/Tokenizer that categorizes content into numbers, operators, or keywords.

**Code:**
```pseudocode
// Note how the definition order matters if patterns overlap (though here they are distinct).
var t = uc.NewTransformer();

// Define patterns for a simple math language
t.FromTo("{d: {@Number}}", "[NUM:{d}]");
t.FromTo("{op: + | - | * | / }", "[OP:{op}]");
t.FromTo("print", "[CMD:PRINT]"); // Specific keyword

var code = "print 10 + 20";
wl(t.Transform(code))
```

**Output:**
```
[CMD:PRINT] [NUM:10] [OP:+] [NUM:20]
```

---

### Example ID: 229

**Description:** Testing the "Last In, First Out" precedence rule with overlapping anchors.

**Code:**
```pseudocode
var t = uc.NewTransformer();

// Priority Test: All start with "An"
// 1. Defined first (lowest priority for same start)
t.FromTo("An {item}", "Match1: {item}"); 

// 2. Defined second
t.FromTo("An {item}.", "Match2: {item}");

// 3. Defined last (Highest priority for same start)
t.FromTo("An orange.", "Match3: orange");

// Input text
var txt = "An orange. An apple. An elephant.";

// "An orange." matches Rule 3 (Specific, defined last)
// "An apple." fails Rule 3, matches Rule 2 (Ending in dot)
// If input is "An elephant" (no dot), it falls back to Rule 1.

wl(t.Transform("An orange."))   // Match3: Orange
wl(t.Transform("An apple."))    // Match2: apple
wl(t.Transform("An elephant"))  // Match1: elephant
```

**Output:**
```
Match3: orange
Match2: apple
Match1: elephant
```

---

### Example ID: 230

**Description:** Basic Key-Value extraction using a colon as an anchor.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// "ID" and ":" are Anchors. "{id}" is the Variable.
t.FromTo("ID: {id}", "Found ID: {id}");
wl(t.Transform("ID: 12345").@Text()) 
```

**Output:**
```
Found ID: 12345
```

---

### Example ID: 231

**Description:** Parsing a standard connection string. Note how the semicolon acts as both an anchor and a natural statement separator.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Anchors: "Server", "=", ";", "Database"
// Variables: {srv}, {db}
t.FromTo("Server={srv};Database={db};", 
         "Connecting to database '{db}' on server '{srv}'...");

var connStr = "Server = LocalHost; Database = MyData;";
wl(t.Transform(connStr).@Text())
// Note: Spaces around '=' handled automatically by default tokenization.
```

**Output:**
```
Connecting to database 'MyData' on server 'LocalHost'...
```

---

### Example ID: 232

**Description:** Testing **Statement Separators** vs **Constraints**.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// 1. Separator Stop: {v} stops at newline (default separator)
t.FromTo("Value: {v}", "Captured: [{v}]");
wl(t.Transform([verbatim]Value: 100
Value: 200[/verbatim]).@Text())

// 2. Constraint vs Ambiguity: 
// {a}{b} is currently ambiguous (usually {a} eats everything).
// {a:2}{b:1} is deterministic.
t.FromTo("{a:2}{b:1}", "A:[{a}], B:[{b}]");
wl(t.Transform("one two three"))
```

**Output:**
```
Captured: [100]
Captured: [200]
A:[one two], B:[three]
```

---

### Example ID: 234

**Description:** Using **Conditional Blocks** to format an optional title.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Pattern: Name followed optionally by a Title in parens.
t.FromTo("Name: {n} [({title})]", 
         "User: {n} {title:[Title: {title}]}");

// Case 1: Title exists
wl(t.Transform("Name: Alice (Manager)")) 

// Case 2: Title missing
wl(t.Transform("Name: Bob"))
// (The entire "[Title: ...]" block is omitted)
```

**Output:**
```
User: Alice [Title: Manager]
User: Bob
```

---

### Example ID: 236

**Description:** Matching one of several keywords.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("Status: { OK | Error | Pending }", "Found Status");

wl(t.Transform("Status: OK"))    // Output: Found Status
wl(t.Transform("Status: Error")) // Output: Found Status
wl(t.Transform("Status: Fail"))  // No Match (Output unchanged)
```

**Output:**
```
Found Status
Found Status
Status: Fail
```

---

### Example ID: 237

**Description:** Parsing boolean values that might be represented differently.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Normalize "True/Yes/On" to "TRUE" and "False/No/Off" to "FALSE"
t.FromTo("{ True | Yes | On }", "TRUE");
t.FromTo("{ False | No | Off }", "FALSE");

wl(t.Transform("System is On"))    // Output: System is TRUE
wl(t.Transform("Power is False"))  // Output: Power is FALSE
```

**Output:**
```
System is TRUE
Power is FALSE
```

---

### Example ID: 238

**Description:** Nested alternatives and variable capture.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Pattern: "Set" followed by (Color OR (Size followed by Big/Small))
// Note: Nesting syntax { A | { B | C } } validation
t.FromTo("Set { Color | Size { Big | Small } }", "Matched");

wl(t.Transform("Set Color"))      // Match
wl(t.Transform("Set Size Big"))   // Match
wl(t.Transform("Set Size Medium"))// No Match
```

**Output:**
```
Matched
Matched
Set Size Medium
```

---

### Example ID: 239

**Description:** Handling an optional trailing semicolon.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("Statement: {val} [;]", "Found: {val}");

wl(t.Transform("Statement: x = 1;")) // Output: Found: x = 1
wl(t.Transform("Statement: y = 2"))  // Output: Found: y = 2
```

**Output:**
```
Found: x = 1
Found: y = 2
```

---

### Example ID: 240

**Description:** Parsing names with an optional middle name.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Matches "First Last" OR "First Middle Last"
// Constraint Note: We use {name:1} to ensure each variable captures exactly one token.
// Replacement Note: We use {middle: {middle}} instead of just {middle} to prepend
// a space only if the middle name exists.
t.FromTo("Name: {first:1} [{middle:1}] {last:1}",
         "User: {last}, {first}{middle: {middle}}"); 

wl(t.Transform("Name: John Doe")) 
wl(t.Transform("Name: John Quincy Adams")) 
```

**Output:**
```
User: Doe, John
User: Adams, John Quincy
```

---

### Example ID: 241

**Description:** Nested optional blocks.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Pattern: A, optionally followed by B, which is optionally followed by C.
// Valid inputs: "A", "A B", "A B C". Invalid: "A C" (since C requires B).
t.FromTo("A [ B [ C ] ]", "Matched");

wl(t.Transform("A"))     // Matched
wl(t.Transform("A B"))   // Matched
wl(t.Transform("A B C")) // Matched
wl(t.Transform("A C"))   // Matched C
```

**Output:**
```
Matched
Matched
Matched
Matched C
```

---

### Example ID: 242

**Description:** Grouping alternatives to limit scope.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Matches "File Open" or "File Close". 
// Capture needs explicit naming.
t.FromTo("File {cmd: Open | Close }", "Command: {cmd}");

wl(t.Transform("File Open"))
wl(t.Transform("File Close"))
```

**Output:**
```
Command: Open
Command: Close
```

---

### Example ID: 243

**Description:** Nested grouping for complex commands.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Pattern: "Set" followed by (Color OR (Size followed by Big/Small))
t.FromTo("Set {prop: Color | Size { Big | Small } }", "Property: {prop}");

wl(t.Transform("Set Color"))
wl(t.Transform("Set Size Big"))
wl(t.Transform("Set Size Small"))
```

**Output:**
```
Property: Color
Property: Size Big
Property: Size Small
```

---

### Example ID: 244

**Description:** Recursive Nesting: Alternation -> Optional -> Alternation.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Structure:
// 1. Alternation: "Open" OR "Save"
// 2. Inside "Open": Optional "Recent"
// 3. Inside "Recent": Alternation "File" OR "Project"
var pattern = "Menu { Open [ Recent {type: File | Project } ] | Save }";

t.FromTo(pattern, "Action Detected");

wl(t.Transform("Menu Save"))                 // Match (Simple Alternation)
wl(t.Transform("Menu Open"))                 // Match (Optional omitted)
wl(t.Transform("Menu Open Recent File"))     // Match (Deep nesting)
wl(t.Transform("Menu Open Recent Project"))  // Match (Deep nesting alt)
```

**Output:**
```
Action Detected
Action Detected
Action Detected
Action Detected
```

---

### Example ID: 245

**Description:** Matching tokens by category.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Match a word (Alpha) followed by equals and a Number (Literal)
t.FromTo("{@Alpha} = {@Number}", "Assignment Detected");

wl(t.Transform("x = 10")) 
```

**Output:**
```
Assignment Detected
```

---

### Example ID: 246

**Description:** Customizing token definitions (e.g., treating hyphens as part of a word).

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Now capture it using the {@Alpha} category
t.FromTo("{@Alpha:w}", "<{w}>");

wl("Before:")
wl(t.Transform("1. Start-Up 'big ideas' well-knwon."))

// Define a new token pattern for hyphenated words
// We assign it to the 'AlphaNumeric' category so it behaves like a word
t.@Tokens().Add("[a-zA-Z-]+", TokenType::AlphaNumeric);
wl("After:")
wl(t.Transform("1. Start-Up 'big ideas' well-knwon."))
```

**Output:**
```
Before:
1. <Start>-<Up> 'big ideas' <well>-<knwon>.
After:
1. <Start-Up> 'big ideas' <well-knwon>.
```

---

### Example ID: 247

**Description:** Handling Brackets and Literals.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Capture a function call. 
// {@Alpha} matches the name. 
// '(' and ')' are Bracket tokens that ensure the content is captured correctly.
t.FromTo("{@Alpha:func} ( {args} )", "Call: {func} with {args}");

wl(t.Transform("myfunc('Hello World', (x + y) * 2 )"))
```

**Output:**
```
Call: myfunc with 'Hello World', (x + y) * 2
```

---

### Example ID: 250

**Description:** Extracting keys from a key-value list where keys must be identifiers.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Capture the alphanumeric key and any literal value
t.FromTo("{@Alpha:key} = {@Literal:val}", "KEY:[{key}] VAL:[{val}]");

var input = "Timeout = 100; User = 'Admin'";
wl(t.Transform(input))
```

**Output:**
```
KEY:[Timeout] VAL:[100]; KEY:[User] VAL:['Admin']
```

---

### Example ID: 251

**Description:** (Real World: Currency Formatter) Finding raw numbers in a text stream and converting them to a formatted currency string.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("Price: {@Number:amt}", "Price: ${amt}");

var(string, input) = "Item A Price: 19.99, Item B Price: 5"
wl(t.Transform(input))
```

**Output:**
```
Item A Price: $19.99, Item B Price: $5
```

---

### Example ID: 252

**Description:** Finding instances where there are two or more consecutive whitespace tokens and reducing them to a single space.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Match two whitespace tokens and replace with one space
t.FromTo("{@Whitespace}", " ");

var(string, messy) = "var    x   =  100;"
wl(t.Transform(messy))
```

**Output:**
```
var x = 100;
```

---

### Example ID: 255

**Description:** Quick Start

**Code:**
```pseudocode
// Create a new instance
NewUsing(uCalc, calc)

// Evaluate an expression
wl(calc.Eval("2 + 3"))
End Using
```

**Output:**
```
5
```

---

### Example ID: 256

**Description:** Creating isolated evaluation contexts.

**Code:**
```pseudocode
New(uCalc, main)
main.DefineVariable("rate = 0.05");

var scenarioA = main.Clone();
var scenarioB = main.Clone();

scenarioA.DefineVariable("rate = 0.10");
scenarioB.DefineVariable("rate = 0.20");

wl("A: ", scenarioA.Eval("1000 * rate"))
wl("B: ", scenarioB.Eval("1000 * rate"))
wl("Main: ", main.Eval("1000 * rate"))
main.Release();
scenarioA.Release();
scenarioB.Release();

```

**Output:**
```
A: 100
B: 200
Main: 50
```

---

### Example ID: 258

**Description:** Registers a handler to log when division by zero occurs.

**Code:**
```pseudocode
[head]
[callback:u LogAndResume]
wl("Logged error: ", uc.@Error().@Message())
uc.@Error().@Response(ErrorHandlerResponse::Resume);
[/callback]

[body]
uc.@Error().@TrapOnDivideByZero(true);
uc.@Error().AddHandler(LogAndResume);

wl("Start")
var Result = uc.Eval("5/0");   // Division by zero
wl("End")
```

**Output:**
```
Start
Logged error: Division by 0
End
```

---

### Example ID: 260

**Description:** Verifying alias removal and fallback behavior.

**Code:**
```pseudocode
uc.DefineVariable("a = 100");

var aliasB = uc.CreateAlias("b", "a");

wl("Before release: ", uc.EvalStr("b"))
aliasB.Release();
wl("After release: ", uc.EvalStr("b"))
```

**Output:**
```
Before release: 100
After release: Undefined identifier
```

---

### Example ID: 269

**Description:** Internal Test: Verifies the stack-like (LIFO) behavior of default instances using a scoped object.

**Code:**
```pseudocode
// Original default instance
uCalc::@DefaultInstance().DefineVariable("id = 'Original'");
wl("Current Default ID: ", uCalc::@DefaultInstance().EvalStr("id"))

// Push a new default instance onto the stack
New(uCalc, ucA)
ucA.DefineVariable("id = 'Instance A'");
ucA.@IsDefault(true);
wl("Current Default ID: ", uCalc::@DefaultInstance().EvalStr("id"))

// The 'NewUsing' block creates a temporary, scoped default instance

   // The following instance will be auto-released at the end of the block
  NewUsing(uCalc, ucB)
  ucB.DefineVariable("id = 'Instance B (temp)'");
  ucB.@IsDefault(true); // Pushes 'ucB' onto the stack
  wl("Current Default ID: ", uCalc::@DefaultInstance().EvalStr("id"))
End Using

// 'ucB' has gone out of scope, so the default reverts to the previous one ('ucA')
wl("Current Default ID (after scope exit): ", uCalc::@DefaultInstance().EvalStr("id"))

// Manually unset 'ucA'
ucA.@IsDefault(false);
wl("Current Default ID (after unset): ", uCalc::@DefaultInstance().EvalStr("id"))
```

**Output:**
```
Current Default ID: Original
Current Default ID: Instance A
Current Default ID: Instance B (temp)
Current Default ID (after scope exit): Instance A
Current Default ID (after unset): Original
```

---

### Example ID: 270

**Description:** Shows the initial count of default instances upon application startup.

**Code:**
```pseudocode
// By default, a single uCalc instance is always available on the stack.
wl("Initial default instance count: ", uCalc::@DefaultCount())
```

**Output:**
```
Initial default instance count: 1
```

---

### Example ID: 271

**Description:** Manage separate parser contexts for different application modules.

**Code:**
```pseudocode
// --- Main Application Context ---
// Starting with the 'uc' object as the initial default.
uCalc::@DefaultInstance().DefineConstant("PI = 3.14159");
wl("Initial Count: ", uCalc::@DefaultCount())

// --- A Plugin needs a temporary, isolated context ---
NewUsing(uCalc, moduleCalc)
moduleCalc.@IsDefault(true); // Push the new instance onto the stack.
wl("Count after module pushes new default: ", uCalc::@DefaultCount())

// The module's context is now active.
// uCalc::DefaultInstance() would now return 'moduleCalc'.
End Using

// When 'moduleCalc' goes out of scope, it's destroyed and automatically
// removed from the stack, restoring the previous default.

wl("Count after module instance is disposed: ", uCalc::@DefaultCount())

// Verify the original default instance is active again.
var result = uCalc::@DefaultInstance().EvalStr("PI");
wl("Original context restored. PI = ", result)
```

**Output:**
```
Initial Count: 1
Count after module pushes new default: 2
Count after module instance is disposed: 1
Original context restored. PI = 3.14159
```

---

### Example ID: 272

**Description:** Internal Test: Verify stack count during creation, stacking, and clearing.

**Code:**
```pseudocode
wl("Initial: ", uCalc::@DefaultCount())

// The implicit 'uc' is the first default. Pushing it again adds to the stack.
uc.@IsDefault(true);
wl("After pushing 'uc' again: ", uCalc::@DefaultCount())

New(uCalc, ucB)
ucB.@IsDefault(true);
wl("After pushing ucB: ", uCalc::@DefaultCount())

New(uCalc, ucC)
ucC.@IsDefault(true);
wl("After pushing ucC: ", uCalc::@DefaultCount())

// Clear all user-defined defaults, leaving only the mandatory root instance.
uCalc::DefaultClear();
wl("After Clear: ", uCalc::@DefaultCount())
```

**Output:**
```
Initial: 1
After pushing 'uc' again: 2
After pushing ucB: 3
After pushing ucC: 4
After Clear: 1
```

---

### Example ID: 273

**Description:** Inspecting the stack depth as new defaults are added and cleared

**Code:**
```pseudocode
// Check initial state (Root instance only)
wl(uCalc::@DefaultCount()) 

// Push the current 'uc' instance onto the stack
uc.@IsDefault(true);
wl(uCalc::@DefaultCount()) 

// Create a new instance and push it
New(uCalc, ucB)
ucB.@IsDefault(true);
wl(uCalc::@DefaultCount())

// Create another instance and push it
New(uCalc, ucC)
ucC.@IsDefault(true);
wl(uCalc::@DefaultCount()) 

// Clear all custom defaults, reverting to the root instance
uCalc::DefaultClear();
wl(uCalc::@DefaultCount())
```

**Output:**
```
1
2
3
4
1
```

---

### Example ID: 274

**Description:** Quick Start: Getting and Setting the Default Type

**Code:**
```pseudocode
// 1. Check startup default (usually Double)
wl("Start: ", uc.@DefaultDataType().@Name())

// 2. Change default to 32-bit Integer
uc.SetDefaultDataType(BuiltInType::Integer_32);
wl("New: ", uc.@DefaultDataType().@Name())

// 3. Reset to Double using string shortcut
uc.SetDefaultDataType("Double");
wl("Reset: ", uc.@DefaultDataType().@Name())

```

**Output:**
```
Start: double
New: int
Reset: double
```

---

### Example ID: 276

**Description:** Internal Test: Default Type Scope and Isolation

**Code:**
```pseudocode
// Create a separate instance to verify isolation
New(uCalc, uc2)

// Set main instance to String
uc.SetDefaultDataType("String");

// Set second instance to Int32
uc2.SetDefaultDataType("Int32");

wl("uc1 Default: ", uc.@DefaultDataType().@Name())
wl("uc2 Default: ", uc2.@DefaultDataType().@Name())

uc2.DefineFunction("Add(a, b) = a + b");
wl("Numeric Add: ", uc2.EvalStr("Add(5, 5)"))

// Check Eval behavior with String default
// "5" + "5" should be string concatenation "55"
uc.DefineFunction("Add(a, b) = a + b");
wl("String Add: ", uc.EvalStr("Add(5, 5)"))
```

**Output:**
```
uc1 Default: string
uc2 Default: int
Numeric Add: 10
String Add: 55
```

---

### Example ID: 277

**Description:** Introspection and conversion using standard types

**Code:**
```pseudocode
// Inspect basic properties of built-in types
wl(uc.DataTypeOf(BuiltInType::Integer_8u).@Name())
wl(uc.DataTypeOf(BuiltInType::Integer_32).@ByteSize())

// Testing edge case conversions mentioned in development notes
// Also string conversion behavior for signed vs unsigned and complex types
wl(uc.DataTypeOf(BuiltInType::Integer_8u).ToString("-1"))
wl(uc.DataTypeOf(BuiltInType::Integer_16u).ToString("-1"))
wl(uc.DataTypeOf(BuiltInType::String).ToString("-1"))
wl(uc.DataTypeOf(BuiltInType::Boolean).ToString("-1"))
```

**Output:**
```
int8u
4
255
65535
-1
true
```

---

### Example ID: 278

**Description:** Checking variable types against BuiltInType

**Code:**
```pseudocode
// 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())
   wl("Variable 'myVar' is an Int16.");
else
   wl("Type mismatch.");
end if
```

**Output:**
```
Variable 'myVar' is an Int16.
```

---

### Example ID: 284

**Description:** Practical: Introspecting variables and functions.

**Code:**
```pseudocode
// Define a variable and a function
uc.DefineVariable("myVar As Int16 = 55");
uc.DefineFunction("myFunc(x) = x * 10.5"); // Implicitly returns Double

// Inspect their types dynamically
var typeVar = uc.DataTypeOf("myVar");
var typeFunc = uc.DataTypeOf("myFunc");

wl("Variable Type: ", typeVar.@Name())
wl("Function Return: ", typeFunc.@Name())

// Check specific properties
if (bool(typeVar.@BuiltInTypeEnum() == BuiltInType::Integer_16))
   wl("Variable is strictly a 16-bit integer.")
end if
```

**Output:**
```
Variable Type: int16
Function Return: double
Variable is strictly a 16-bit integer.
```

---

### Example ID: 285

**Description:** Internal Test: aliases and comparison logic.

**Code:**
```pseudocode
// "Int" is a synonym for Int32
wl(uc.DataTypeOf("Int").@Name())

// Boolean logic expression returns bool type
wl(uc.DataTypeOf("3 < 10").@Name())

// String concatenation returns string
wl(uc.DataTypeOf(" 'A' + 'B' ").@Name())

// Complex number syntax
wl(uc.DataTypeOf("5 + 7 * #i").@Name())
```

**Output:**
```
int
bool
string
complex
```

---

### Example ID: 286

**Description:** Quickly defines the mathematical constant PI and uses it in a simple calculation.

**Code:**
```pseudocode
uc.DefineConstant("PI = 3.14159");
wl(uc.Eval("2 * PI"))
```

**Output:**
```
6.28318
```

---

### Example ID: 287

**Description:** Defines several application-level configuration constants for use in expressions.

**Code:**
```pseudocode
uc.DefineConstant("MAX_USERS = 100");
uc.DefineConstant("API_VERSION = 'v2.1'");
uc.DefineConstant("ENABLE_LOGGING = true");

wl("Configuration Settings:")
wl("Max Users: ", uc.Eval("MAX_USERS"))
wl("API Version: ", uc.EvalStr("API_VERSION"))
wl("Logging Enabled: ", uc.EvalStr("ENABLE_LOGGING"))

// Use in a conditional expression
var(int, currentUserCount) = 99;
if (uc.EvalStr(to_string(currentUserCount) + " < MAX_USERS") == "true")
    wl("System capacity is OK.")
end if
```

**Output:**
```
Configuration Settings:
Max Users: 100
API Version: v2.1
Logging Enabled: true
System capacity is OK.
```

---

### Example ID: 288

**Description:** Internal Test: Validates that end-users cannot modify a locked constant.

**Code:**
```pseudocode
uc.DefineConstant("LOCKED_VAL = 1000");
wl("Initial value: ", uc.Eval("LOCKED_VAL"))

// 1. End-user attempts to assign a value. This should fail.
uc.Eval("LOCKED_VAL = 2000");
wl("Error after assignment attempt: ", uc.@Error().@Message())
wl("Value remains unchanged: ", uc.Eval("LOCKED_VAL"))

```

**Output:**
```
Initial value: 1000
Error after assignment attempt: Value cannot be assigned here
Value remains unchanged: 1000
```

---

### Example ID: 289

**Description:** Sets and retrieves a description for the main uCalc object.

**Code:**
```pseudocode
// Assign a description to the main uCalc instance
uc.@Description("Primary evaluator for financial calculations");

// Retrieve and print the description
wl(uc.@Description())
```

**Output:**
```
Primary evaluator for financial calculations
```

---

### Example ID: 292

**Description:** Sample example

**Code:**
```pseudocode
wl("This is a sample example")
```

**Output:**
```
This is a sample example
```

---

### Example ID: 293

**Description:** Defining a simple variable and function.

**Code:**
```pseudocode
// Define a variable and a function using the core Define method
uc.Define("Variable: my_var = 100");
uc.Define("Function: square(x) = x * x");

wl(uc.Eval("my_var * square(5)"))
```

**Output:**
```
2500
```

---

### Example ID: 295

**Description:** Internal Test: Verifying 'Overwrite' for interdependent definitions in a spreadsheet simulation.

**Code:**
```pseudocode
// Define interdependent 'cells' using the Overwrite command.
uc.Define("Overwrite ~~ Function: A1() = 10");
uc.Define("Overwrite ~~ Function: B1() = A1() * 2");
uc.Define("Overwrite ~~ Function: C1() = A1() + B1()");

wl("Initial C1: ", uc.Eval("C1()")) // Should be 10 + (10 * 2) = 30

// Now, overwrite the source cell A1. All dependent cells should automatically update.
uc.Define("Overwrite ~~ Function: A1() = 50");

wl("Updated B1: ", uc.Eval("B1()")) // Should now be 50 * 2 = 100
wl("Updated C1: ", uc.Eval("C1()")) // Should now be 50 + 100 = 150
```

**Output:**
```
Initial C1: 30
Updated B1: 100
Updated C1: 150
```

---

### Example ID: 296

**Description:** A minimal example defining a function inline to calculate the area of a rectangle.

**Code:**
```pseudocode
uc.DefineVariable("x = 5");
uc.DefineFunction("Area(length, width) = length * width");
wl(uc.Eval("Area(4, x) + 7"))
```

**Output:**
```
27
```

---

### Example ID: 297

**Description:** Demonstrates defining a function that is implemented by a native callback in the host application.

**Code:**
```pseudocode
[head]
[callback MyAreaCallback]
  var length = cb.Arg(1);
  var width = cb.Arg(2);
  cb.Return(length * width);
[/callback]

[body]
// The signature is defined, but the logic is provided by 'MyAreaCallback'.
uc.DefineFunction("Area(x, y)", MyAreaCallback);
wl(uc.Eval("Area(3, 4)"))
```

**Output:**
```
12
```

---

### Example ID: 298

**Description:** Shows how to create overloaded functions that uCalc distinguishes based on parameter count and type.

**Code:**
```pseudocode
// Overload for two numbers
uc.DefineFunction("Combine(x, y) = x + y");

// Overload for two strings
uc.DefineFunction("Combine(x As String, y As String) As String = x + y");

// Overload for three numbers
uc.DefineFunction("Combine(x, y, z) = x + y + z");

wl("Two numbers: ", uc.EvalStr("Combine(5, 10)"))
wl("Two strings: ", uc.EvalStr("Combine('Hello, ', 'World!')"))
wl("Three numbers: ", uc.EvalStr("Combine(5, 10, 20)"))
```

**Output:**
```
Two numbers: 15
Two strings: Hello, World!
Three numbers: 35
```

---

### Example ID: 299

**Description:** Defines a recursive Factorial function using the IIf function for conditional logic.

**Code:**
```pseudocode
uc.DefineFunction("Factorial(n) = IIf(n > 1, n * Factorial(n - 1), 1)");
wl(uc.Eval("Factorial(5)"))
```

**Output:**
```
120
```

---

### Example ID: 305

**Description:** A minimal example defining a variable and using it in an expression.

**Code:**
```pseudocode
uc.DefineVariable("x = 10");
wl(uc.Eval("x * 5"))
```

**Output:**
```
50
```

---

### Example ID: 306

**Description:** Defines variables with explicit types, inferred types, and default types.

**Code:**
```pseudocode
// Explicit type definition
uc.DefineVariable("explicitInt As Int = 123");

// Type inferred from the initial string value
uc.DefineVariable("inferredStr = 'hello'");

// Type defaults to Double as no type or value is given
var defaultVar = uc.DefineVariable("defaultVar");

wl("explicitInt type: ", uc.ItemOf("explicitInt").@DataType().@Name())
wl("inferredStr type: ", uc.ItemOf("inferredStr").@DataType().@Name())
wl("defaultVar type: ", defaultVar.@DataType().@Name())
```

**Output:**
```
explicitInt type: int
inferredStr type: string
defaultVar type: double
```

---

### Example ID: 310

**Description:** A quick example demonstrating how to set and get a description on a variable.

**Code:**
```pseudocode
// Define a variable and chain the Description() call to set metadata
var myVar = uc.DefineVariable("x = 10").SetDescription("Stores the current iteration count.");

// Retrieve and display the description
wl("Description for 'x': ", myVar.@Description())
```

**Output:**
```
Description for 'x': Stores the current iteration count.
```

---

### Example ID: 318

**Description:** An internal test to confirm that ErrorExpression returns an empty string for an error triggered manually by a user function during evaluation.

**Code:**
```pseudocode
[head]
[callback MyFunc]
  // This error occurs during evaluation, not parsing.
  cb.@Error().Raise("Manual evaluation failure!");
[/callback]

[callback:u MyHandler]
  wl("Handler triggered for error: ", uc.@Error().@Message())
  wl("ErrorExpression() returned: '", uc.@Error().@Expression(), "'")
  wl("Is expression empty? ", bool(uc.@Error().@Expression() == ""))
[/callback]

[body]
uc.DefineFunction("MyFunc()", MyFunc);
uc.@Error().AddHandler(MyHandler);

// The expression 'MyFunc()' itself is valid syntactically.
wl(uc.EvalStr("MyFunc()"))
```

**Output:**
```
Handler triggered for error: Manual evaluation failure!
ErrorExpression() returned: ''
Is expression empty? True
Manual evaluation failure!
```

---

### Example ID: 321

**Description:** Capturing both parsing-stage and evaluation-stage errors to see how ErrorLocation behaves differently.

**Code:**
```pseudocode
[head]
[callback:u MyErrorHandler]
wl("--- Error Captured ---")
wl("Message: ", uc.@Error().@Message())
wl("Symbol: '", uc.@Error().@Symbol(), "'")
wl("Location: ", uc.@Error().@Location())
wl("Expression: '", uc.@Error().@Expression(), "'")
[/callback]

[body]
uc.@Error().AddHandler(MyErrorHandler);

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

wl("")
wl("Demonstrating an EVALUATION error:")
uc.@Error().@TrapOnDivideByZero(true);
uc.EvalStr("5/0");
```

**Output:**
```
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: ''
```

---

### Example ID: 322

**Description:** Demonstrates getting the last error message after a failed operation.

**Code:**
```pseudocode
// Attempt to evaluate an expression with unbalanced parenthesis causing a syntax error.
uc.EvalStr("5 * (10 +");

// Check the error message from the last operation.
wl("Last error message: ", uc.@Error().@Message())
```

**Output:**
```
Last error message: Bracket delimiter error
```

---

### Example ID: 323

**Description:** Retrieves the generic message for a specific error code and compares it to the last error message.

**Code:**
```pseudocode
// Retrieve the built-in message for a specific error code, without triggering an error.
wl("Generic 'Undefined Identifier' message: ", uc.@Error().GetMessage(ErrorCode::Undefined_Identifier))

// Now, trigger a specific error by using an undefined variable.
uc.EvalStr("MyUndefinedVar + 5");

// Check the message and number for the last error that occurred.
wl("Last error message: ", uc.@Error().@Message())
wl("Last error number: ", [c](int)[/c][vb]CType([/vb]uc.@Error().@Code()[vb], Integer)[/vb])
```

**Output:**
```
Generic 'Undefined Identifier' message: Undefined identifier
Last error message: Undefined identifier
Last error number: 258
```

---

### Example ID: 324

**Description:** Internal Test: Verifies that the error state is correctly cleared after a subsequent successful operation.

**Code:**
```pseudocode
// Internal Test: Verify error state is cleared
wl("--- Testing Error State Lifecycle ---")

// 1. Trigger a division-by-zero error.
uc.@Error().@TrapOnDivideByZero(true);
uc.EvalStr("1 / 0");
wl("Message after 1/0: '", uc.@Error().@Message(), "'")
wl("Error number is not None: ", bool(uc.@Error().@Code() != ErrorCode::None))

// 2. Perform a successful operation, which should clear the previous error state.
uc.EvalStr("1 + 1");

// 3. Verify the error message and number have been reset.
wl("Message after successful op: '", uc.@Error().@Message(), "'")
wl("Error number is now None: ", bool(uc.@Error().@Code() == ErrorCode::None))
```

**Output:**
```
--- Testing Error State Lifecycle ---
Message after 1/0: 'Division by 0'
Error number is not None: True
Message after successful op: 'No error'
Error number is now None: True
```

---

### Example ID: 325

**Description:** Checking the error code for a simple syntax error using a callback.

**Code:**
```pseudocode
[head]
[callback:u MyHandler]
  // Retrieve the error code as an integer for display
  var(int, code) = [C](int)[/C]uc.@Error().@Code();
  wl("Caught Error Code: ", code)
  
  // Compare the error code against the ErrorCode enum for logic
  if (uc.@Error().@Code() == ErrorCode::Syntax_Error)
     wl("This was a syntax error.")
  end if
[/callback]

[body]
// Register the error handler
uc.@Error().AddHandler(MyHandler);

// Intentionally cause a syntax error, which will trigger the handler
wl(uc.EvalStr("5 *"))
```

**Output:**
```
Caught Error Code: 257
This was a syntax error.
Syntax error
```

---

### Example ID: 326

**Description:** Creating an error handler that automatically defines variables on the fly by checking for an 'Undefined Identifier' error.

**Code:**
```pseudocode
[head]
[callback:u AutoDefineHandler]
  // Check if the error is specifically an undefined identifier
  if (uc.@Error().@Code() == ErrorCode::Undefined_Identifier)
    // If so, define the missing variable and instruct uCalc to resume
    wl("Auto-defining variable: '", uc.@Error().@Symbol(), "'")
    uc.DefineVariable(uc.@Error().@Symbol());
    uc.@Error().@Response(ErrorHandlerResponse::Resume);
  end if
[/callback]

[body]
uc.@Error().AddHandler(AutoDefineHandler);

// 'x' doesn't exist, but the handler will intercept the error and create it.
var Result = uc.EvalStr("x = 10; x * 5");
wl("Result: ", Result)
```

**Output:**
```
Auto-defining variable: 'x'
Result: 50
```

---

### Example ID: 327

**Description:** Internal Test: Verifies that the error code is correctly cleared after a successful operation.

**Code:**
```pseudocode
// Trigger an error and check the code
uc.EvalStr("1+"); 
wl("1. Error code after failure: ", [C](int)[/C]uc.@Error().@Code()[VB].ToString("D")[/VB])

// A successful evaluation should clear the error code
uc.EvalStr("1+1");
wl("2. Error code after success: ", [C](int)[/C]uc.@Error().@Code()[VB].ToString("D")[/VB])

// Trigger a different type of error
uc.@Error().@TrapOnDivideByZero(true);
uc.EvalStr("1/0");
wl("3. Error code after new failure: ", [C](int)[/C]uc.@Error().@Code()[VB].ToString("D")[/VB])

// A successful definition should also clear the error code
uc.DefineVariable("x=5"); 
wl("4. Error code after successful definition: ", [C](int)[/C]uc.@Error().@Code()[VB].ToString("D")[/VB])
```

**Output:**
```
1. Error code after failure: 257
2. Error code after success: 0
3. Error code after new failure: 8
4. Error code after successful definition: 0
```

---

### Example ID: 329

**Description:** Practical: Creates a robust error handler that automatically defines variables on-the-fly when an 'Undefined Identifier' error occurs.

**Code:**
```pseudocode
[head]
// This error handler allows you to use variables that were not
// explicitly defined previously by defining unrecognized identifiers
// as variables instead of returning an error.
[callback:u AutoVariableDef]
   if (uc.@Error().@Code() == ErrorCode::Undefined_Identifier)
      uc.DefineVariable(uc.@Error().@Symbol());
      uc.@Error().@Response(ErrorHandlerResponse::Resume);
   end if
[/callback]

[body]
uc.@Error().AddHandler(AutoVariableDef);
// The handler will automatically define 'AutoTest' on first use.
wl(uc.Eval("AutoTest = 123"))
wl(uc.Eval("AutoTest * 1000"))
```

**Output:**
```
123
123000
```

---

### Example ID: 334

**Description:** Quickly evaluates several basic mathematical and function-based expressions.

**Code:**
```pseudocode
// Eval provides a direct way to compute results from strings.
wl(uc.Eval("1+1"))
wl(uc.Eval("5*(3+9)^2"))
wl(uc.Eval("Sqrt(16) + Sin(0)"))
wl(uc.Eval("Length('This is a test')"))
```

**Output:**
```
2
720
4
14
```

---

### Example ID: 335

**Description:** Calculates simple interest by defining variables and then evaluating an expression string that uses them.

**Code:**
```pseudocode
// 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");
wl("Total Interest: ", interest)
```

**Output:**
```
Total Interest: 4600
```

---

### Example ID: 337

**Description:** Demonstrates basic, one-line evaluations for numeric, string, and boolean expressions.

**Code:**
```pseudocode
// Basic arithmetic
wl(uc.EvalStr("15 * (4 + 3)"))
// String manipulation
wl(uc.EvalStr("UCase('hello') + ', world!'"))
// Boolean logic
wl(uc.EvalStr("10 > 5 AndAlso 'a' < 'b'"))
```

**Output:**
```
105
HELLO, world!
true
```

---

### Example ID: 338

**Description:** Calculates a total price using predefined variables and demonstrates the effect of output formatting.

**Code:**
```pseudocode
// 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
wl("Formatted Total: ", uc.EvalStr(expression, true))

// Evaluate with formatting disabled
wl("Raw Total: ", uc.EvalStr(expression, false))
```

**Output:**
```
Formatted Total: $162.342525
Raw Total: 162.342525
```

---

### Example ID: 340

**Description:** Quick Start: Inspects the regex pattern for a single, common token type (alphanumeric identifiers).

**Code:**
```pseudocode
var tokens = uc.@ExpressionTokens();
var alphanumericToken = tokens[TokenType::AlphaNumeric];

wl("The regex for alphanumeric tokens is:")
wl(alphanumericToken.@Regex())
```

**Output:**
```
The regex for alphanumeric tokens is:
[a-zA-Z_][a-zA-Z0-9_]*
```

---

### Example ID: 342

**Description:** Extends the parser to support C-style `0x` hex and `0b` binary notations using a token transformer.

**Code:**
```pseudocode
// Define a token for C-like 0x hex notation
uc.@ExpressionTokens().Add("0x[0-9A-Fa-f]+", TokenType::TokenTransform);
uc.@TokenTransformer().FromTo("{'0x'}{Num:'[0-9A-Fa-f]+'}", "BaseConvert('{Num}', 16)");
wl("0xFF is evaluated as: ", uc.EvalStr("0xFF"))

// Define a token for C++-style 0b binary notation
uc.@ExpressionTokens().Add("0b[01]+", TokenType::TokenTransform);

// Using {@Eval} is more efficient as the conversion happens once during the token transform pass.
uc.@TokenTransformer().FromTo("{'0b'}{Num:'[01]+'}", "{@Eval: BaseConvert(Num, 2)}");
wl("0b1011 is evaluated as: ", uc.EvalStr("0b1011"))

// Note: uCalc has built-in support for hex/binary using # notation (e.g., #hFF, #b1011)
wl("uCalc's built-in #hFF is: ", uc.EvalStr("#hFF"))
```

**Output:**
```
0xFF is evaluated as: 255
0b1011 is evaluated as: 11
uCalc's built-in #hFF is: 255
```

---

### Example ID: 346

**Description:** Demonstrates using `RewindOnChange(true)` to perform recursive-style transformations, such as creating a variadic `AddUp` function.

**Code:**
```pseudocode
var t = uc.@ExpressionTransformer();

// Base case: a single argument
t.FromTo("AddUp({x})", "{x}");

// Recursive case: multiple arguments
// RewindOnChange(true) causes the transformer to re-scan the string after a replacement.
// This allows AddUp(1,2,3) -> (1 + AddUp(2,3)) -> (1 + (2 + AddUp(3))) -> (1 + (2 + 3))
t.FromTo("AddUp({x}, {y})", "({x} + AddUp({y}))").@RewindOnChange(true);

wl("Input: AddUp(1, 2, 3, 4)")
wl("Result: ", uc.Eval("AddUp(1, 2, 3, 4)"))
```

**Output:**
```
Input: AddUp(1, 2, 3, 4)
Result: 10
```

---

### Example ID: 347

**Description:** Internal Test: Verifies that multi-pass transformations work correctly when `RewindOnChange` is enabled for the entire rule set.

**Code:**
```pseudocode
var t = uc.@ExpressionTransformer();

// Enable RewindOnChange for all subsequently added rules
t.@DefaultRuleSet().@RewindOnChange(true);

// Define a chain of simple transformations
t.FromTo("A", "B");
t.FromTo("B", "C");
t.FromTo("C", "D");

// The transformer should apply all rules in sequence: A -> B -> C -> D
var result = t.Transform("A").@Text();
wl("Transform('A') -> ", result)
wl("Is correct: ", bool(result == "D"))
```

**Output:**
```
Transform('A') -> D
Is correct: True
```

---

### Example ID: 348

**Description:** The getter and setter functionality for a single flag.

**Code:**
```pseudocode
// Get the initial state (default is 0, no errors raised)
wl("Initial flags: ", uc.@Error().@FloatingPointErrorsToTrap())

// Enable raising an error for division by zero
uc.@Error().@FloatingPointErrorsToTrap([c](int)[/c][vb]CInt([/vb]ErrorCode::FloatDivisionByZero[vb])[/vb]);

// Verify the new state
wl("Updated flags: ", uc.@Error().@FloatingPointErrorsToTrap())

// Test the behavior
wl("1/0 = ", uc.EvalStr("1/0"))

// Disable the flag by setting it back to 0
uc.@Error().@FloatingPointErrorsToTrap(0);
wl("Flags after reset: ", uc.@Error().@FloatingPointErrorsToTrap())
wl("1/0 after reset = ", uc.EvalStr("1/0"))
```

**Output:**
```
Initial flags: 0
Updated flags: 8
1/0 = Division by 0
Flags after reset: 0
1/0 after reset = inf
```

---

### Example ID: 349

**Description:** Demonstrates enabling multiple floating-point error types and observing the results.

**Code:**
```pseudocode
wl("--- Default Behavior (No Errors Raised) ---")
wl("1/0: ", uc.EvalStr("1/0"))
wl("0/0: ", uc.EvalStr("0/0"))
wl("Overflow (5*10^308): ", uc.EvalStr("5*10^308"))
wl("Underflow (10^-308/10000): ", uc.EvalStr("10^-308/10000"))

wl("")
wl("--- Enable Invalid Operation & Underflow ---")
// You can pass multiple enum members to enable them simultaneously
uc.@Error().SetFloatingPointErrorsToTrap(ErrorCode::FloatInvalid, ErrorCode::FloatUnderflow);
wl("Current flags: ", uc.@Error().@FloatingPointErrorsToTrap()) // Should be 16 (Invalid) + 2 (Underflow) = 18

wl("1/0: ", uc.EvalStr("1/0")) // Not enabled, returns inf
wl("0/0: ", uc.EvalStr("0/0")) // Enabled, raises error
wl("Overflow (5*10^308): ", uc.EvalStr("5*10^308")) // Not enabled, returns inf
wl("Underflow (10^-308/10000): ", uc.EvalStr("10^-308/10000")) // Enabled, raises error
```

**Output:**
```
--- Default Behavior (No Errors Raised) ---
1/0: inf
0/0: nan
Overflow (5*10^308): inf
Underflow (10^-308/10000): 0

--- Enable Invalid Operation & Underflow ---
Current flags: 18
1/0: inf
0/0: Invalid operation
Overflow (5*10^308): inf
Underflow (10^-308/10000): Floating point underflow
```

---

### Example ID: 350

**Description:** Internal Test: Verifies that setting and clearing all possible floating-point flags works correctly.

**Code:**
```pseudocode
// Combine all flags using integer values (or bitwise OR on enums)
var allFlags = [c]2 | 4 | 8 | 16[/c][vb]2 Or 4 Or 8 Or 16[/vb]; // Underflow, Overflow, DivByZero, Invalid
uc.@Error().@FloatingPointErrorsToTrap(allFlags);
wl("All flags set: ", uc.@Error().@FloatingPointErrorsToTrap())

// Test all conditions
wl("Underflow: ", uc.EvalStr("1e-320"))
wl("Overflow: ", uc.EvalStr("1e320"))
wl("DivByZero: ", uc.EvalStr("1/0"))
wl("Invalid: ", uc.EvalStr("0/0"))

// Clear all flags
uc.@Error().@FloatingPointErrorsToTrap(0);
wl("")
wl("All flags cleared: ", uc.@Error().@FloatingPointErrorsToTrap())

// Verify they are cleared
wl("Underflow: ", uc.EvalStr("1e-320"))
wl("Overflow: ", uc.EvalStr("1e320"))
wl("DivByZero: ", uc.EvalStr("1/0"))
wl("Invalid: ", uc.EvalStr("0/0"))
```

**Output:**
```
All flags set: 30
Underflow: Floating point underflow
Overflow: Floating point overflow
DivByZero: Division by 0
Invalid: Invalid operation

All flags cleared: 0
Underflow: 0
Overflow: inf
DivByZero: inf
Invalid: nan
```

---

### Example ID: 351

**Description:** A basic example that prepends text to all numeric output.

**Code:**
```pseudocode
// Define a format that only applies to Double data types.
var doubleType = uc.DataTypeOf("Double");
var fmt = uc.Format("Result = 'Value: ' + Result", doubleType);

wl(uc.EvalStr("10 * 2.5"))
wl(uc.EvalStr("'Hello'")) // String output is unaffected.

// Clean up the format rule
fmt.Release();
wl(uc.EvalStr("10 * 2.5")) // No longer formatted
```

**Output:**
```
Value: 25
Hello
25
```

---

### Example ID: 352

**Description:** Practical: Using the C++ style `Format()` function for currency and text alignment.

**Code:**
```pseudocode
// Rule 1: Format Doubles as currency with two decimal places.
var doubleType = uc.DataTypeOf(BuiltInType::Float_Double);
uc.Format("Result = '$' + Format('{:.2f}', double(Result))", doubleType);

// Rule 2: Center-align strings in a 15-character field padded with '-'.
var strType = uc.DataTypeOf(BuiltInType::String);
uc.Format("Result = Format('{:-^15}', Result)", strType);

wl("Price: ", uc.EvalStr("199.999"))
wl("Discount: ", uc.EvalStr("7.5"))
wl("Label: ", uc.EvalStr("'Summary'"))
```

**Output:**
```
Price: $200.00
Discount: $7.50
Label: ----Summary----
```

---

### Example ID: 353

**Description:** Internal Test: Verifies the layering and precedence of multiple format rules using `InsertAt`.

**Code:**
```pseudocode
var strType = uc.DataTypeOf("String");

// Rule A (will be applied second)
uc.Format("val = '[' + val + ']'");

// Rule B (will be applied first)
uc.Format("val = 'inner:(' + val + ')'");

wl("Default layering: ", uc.EvalStr("'text'"))

// Rule C: Insert this rule at position 0, making it apply LAST.
uc.Format("InsertAt: 0, Def: val = 'outer: {' + val + '}'");

wl("With InsertAt: ", uc.EvalStr("'text'"))
```

**Output:**
```
Default layering: [inner:(text)]
With InsertAt: outer: {[inner:(text)]}
```

---

### Example ID: 366

**Description:** A simple check to see which uCalc instance is the default.

**Code:**
```pseudocode
// The implicit 'uc' object is not the default upon creation.
wl("Is 'uc' the default instance? ", bool(uc.@IsDefault()))

// Create a new uCalc instance. It also won't be the default.
New(uCalc, myCalc);
wl("Is 'myCalc' the default instance? ", bool(myCalc.@IsDefault()));

// Let's get the actual default instance and check it.
var(uCalc, defaultInstance) = uCalc::@DefaultInstance();
wl("Is the instance from uCalc.DefaultInstance the default? ", bool(defaultInstance.@IsDefault()))
```

**Output:**
```
Is 'uc' the default instance? False
Is 'myCalc' the default instance? False
Is the instance from uCalc.DefaultInstance the default? True
```

---

### Example ID: 367

**Description:** Manage different parser configurations by switching the default instance.

**Code:**
```pseudocode
// Setup a "Scientific" configuration
New(uCalc, scientificCalc)
scientificCalc.DefineFunction("sqrt(x) = x^0.5");
scientificCalc.DefineVariable("pi = 3.14159");

// Setup a "Financial" configuration
New(uCalc, financialCalc)
financialCalc.DefineFunction("tax(amount, rate) = amount * (rate/100)");

// Set the scientific calculator as the default
scientificCalc.@IsDefault(true);
wl("Current default is scientific? ", bool(scientificCalc.@IsDefault()))

// Components that rely on the default instance now use the scientific setup.
var(uCalc::Expression, expr1) = "2 * pi";
wl("2 * pi = ", expr1.Evaluate())

// Now, switch the default to the financial calculator
financialCalc.@IsDefault(true);
wl("Current default is scientific? ", bool(scientificCalc.@IsDefault())) // Should be false now
wl("Current default is financial? ", bool(financialCalc.@IsDefault()))

// New components will use the financial setup.
var(uCalc::Expression, expr2) = "tax(50000, 20)";
wl("Tax on 50000 at 20% = ", expr2.Evaluate())
```

**Output:**
```
Current default is scientific? True
2 * pi = 6.28318
Current default is scientific? False
Current default is financial? True
Tax on 50000 at 20% = 10000
```

---

### Example ID: 368

**Description:** Internal Test: Verify the stack-like behavior of the default instance list.

**Code:**
```pseudocode
// Define a variable in the original default to distinguish it.
// Note: This variable won't exist in the implicit 'uc' instance.
uCalc::@DefaultInstance().DefineVariable("id='Original'");
wl("Initial default: ", uCalc::@DefaultInstance().EvalStr("id"));

New(uCalc, ucA);
ucA.DefineVariable("id='A'");
ucA.@IsDefault(true); // Default stack: [Original, A]
wl("Current default: ", uCalc::@DefaultInstance().EvalStr("id"));

New(uCalc, ucB);
ucB.DefineVariable("id='B'");
ucB.@IsDefault(true); // Default stack: [Original, A, B]
wl("Current default: ", uCalc::@DefaultInstance().EvalStr("id"));

New(uCalc, ucC);
ucC.DefineVariable("id='C'");
ucC.@IsDefault(true); // Default stack: [Original, A, B, C]
wl("Current default: ", uCalc::@DefaultInstance().EvalStr("id"));

wl("--- Unsetting instances ---");
// Unset B. The default should remain C.
ucB.@IsDefault(false);
wl("After unsetting B, current default: ", uCalc::@DefaultInstance().EvalStr("id"));

// Unset C. The default should revert to A.
ucC.@IsDefault(false);
wl("After unsetting C, current default: ", uCalc::@DefaultInstance().EvalStr("id"));

// Unset A. Reverts to the original default.
ucA.@IsDefault(false);
wl("After unsetting A, current default: ", uCalc::@DefaultInstance().EvalStr("id"));
```

**Output:**
```
Initial default: Original
Current default: A
Current default: B
Current default: C
--- Unsetting instances ---
After unsetting B, current default: C
After unsetting C, current default: A
After unsetting A, current default: Original
```

---

### Example ID: 374

**Description:** A simple lookup to retrieve a defined variable by its name and display its value.

**Code:**
```pseudocode
uc.DefineVariable("MyVar = 123");

// Retrieve the item by name
var item = uc.ItemOf("MyVar");

// Check if the item was found and print its value
if (item.NotEmpty())
    wl("Value of MyVar is: ", item.Value())
end if
```

**Output:**
```
Value of MyVar is: 123
```

---

### Example ID: 375

**Description:** Use the 'properties' parameter to disambiguate between the infix (binary) and prefix (unary) versions of the minus '-' operator.

**Code:**
```pseudocode
// Get the infix (subtraction) operator and check its operand count
var infixOp = uc.ItemOf("-", [c]ItemIs::Infix[/c][vb]uCalc.Properties(ItemIs::Infix)[/vb]);
w("Infix '-' operator has ", infixOp.@Count())
wl(" operand(s).")

// Get the prefix (negation) operator
var prefixOp = uc.ItemOf("-", [c]ItemIs::Prefix[/c][vb]uCalc.Properties(ItemIs::Prefix)[/vb]);
w("Prefix '-' operator has ", prefixOp.@Count())
wl(" operand(s).")
```

**Output:**
```
Infix '-' operator has 2 operand(s).
Prefix '-' operator has 1 operand(s).
```

---

### Example ID: 384

**Description:** Lists the names of all user-defined and built-in functions.

**Code:**
```pseudocode
// Note: Some items in this list (like bool, or int*) appear more than once or out of chronological
// order because they are aliases (like bool, which is also an alias for boolean)
wl("Defined Functions:")
foreach(var item in uc.GetItems(ItemIs::Function))
   wl(" - ", item.@Name())
end foreach
```

**Output:**
```
Defined Functions:
 - abs
 - acos
 - acosh
 - addptr
 - addressof
 - anytype
 - append
 - append_copy
 - arg
 - argcount
 - asc
 - asin
 - asinh
 - atan
 - atan2
 - atanh
 - back
 - baseconvert
 - bin
 - bool
 - bool
 - int8u
 - c_str
 - cbrt
 - ceil
 - chr
 - clear
 - compare
 - complex
 - conj
 - contains
 - copysign
 - cos
 - cosh
 - define
 - doloop
 - double
 - endswith
 - erase
 - erase_copy
 - erf
 - erfc
 - error
 - eval
 - evalstr
 - evaluate
 - evaluateint
 - evaluatestr
 - exp
 - exp2
 - expm1
 - exprptr
 - fabs
 - fdim
 - file
 - filesize
 - fill
 - find_first_not_of
 - find_first_of
 - find_last_not_of
 - find_last_of
 - single
 - floor
 - fmax
 - fmin
 - fmod
 - forloop
 - format
 - fpclassify
 - frac
 - frexp
 - fromto
 - goto
 - hex
 - hypot
 - iif
 - ilogb
 - imag
 - indexof
 - inf
 - insert
 - insert_copy
 - int
 - int16
 - int16u
 - int
 - int32u
 - int64
 - int64u
 - int8
 - int8u
 - int
 - isfinite
 - isinf
 - isnan
 - isnormal
 - lastindexof
 - lcase
 - ldexp
 - length
 - lgamma
 - llrint
 - llround
 - log
 - log10
 - log1p
 - log2
 - logb
 - lrint
 - lround
 - ltrim
 - max
 - min
 - modf
 - nan
 - nearbyint
 - nextafter
 - nexttoward
 - norm
 - oct
 - omnitype
 - padleft
 - padright
 - parse
 - pointer
 - polar
 - pop
 - pow
 - precedence
 - proj
 - push
 - rand
 - randfromsameseed
 - randomnumber
 - randomseed
 - real
 - remainder
 - remquo
 - repeat
 - replace
 - replace_copy
 - reset
 - rint
 - round
 - rtrim
 - sametypeas
 - scalbln
 - scalbn
 - setvar
 - sgn
 - signbit
 - sin
 - single
 - sinh
 - size_t
 - sizeof
 - sort
 - sqr
 - sqrt
 - startswith
 - str
 - string
 - substr
 - subtractptr
 - swap
 - tan
 - tanh
 - tgamma
 - trim
 - trunc
 - ucalcinstance
 - ucase
 - valueat
 - valueattype
 - void
```

---

### Example ID: 392

**Description:** A simple replacement demonstrating how to swap specific word patterns.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("Hello {name}", "Greetings, {name}!");
wl(t.Transform("Hello World"))
```

**Output:**
```
Greetings, World!
```

---

### Example ID: 396

**Description:** A simple demonstration of parsing an expression and then evaluating it.

**Code:**
```pseudocode
wl("Parsing the expression '100 / 4'...")
NewUsing(uCalc::Expression, parsedExpr("100 / 4"))
//var parsedExpr = uc.Parse("100 / 4");

wl("Evaluating the result...")
wl("Result: ", parsedExpr.Evaluate())
End Using
```

**Output:**
```
Parsing the expression '100 / 4'...
Evaluating the result...
Result: 25
```

---

### Example ID: 403

**Description:** Toggling the error-raising behavior for division by zero.

**Code:**
```pseudocode
// Default behavior: returns infinity
wl("Default: ", uc.EvalStr("1/0"))

// Enable error raising
uc.@Error().@TrapOnDivideByZero(true);
wl("Error Enabled: ", uc.EvalStr("1/0"))

// Disable error raising
uc.@Error().@TrapOnDivideByZero(false);
wl("Error Disabled: ", uc.EvalStr("1/0"))
```

**Output:**
```
Default: inf
Error Enabled: Division by 0
Error Disabled: inf
```

---

### Example ID: 405

**Description:** Internal Test: Verifies that only the division by zero flag is affected, while other floating-point exceptions like overflow remain unchanged by default.

**Code:**
```pseudocode
// Enable only the division by zero error
uc.@Error().@TrapOnDivideByZero(true);

// This should now raise a uCalc error
wl("Test 1 (Div by Zero): ", uc.EvalStr("1/0"))

// This should still return 'inf' by default, as we didn't enable overflow errors
wl("Test 2 (Overflow): ", uc.EvalStr("1e308 * 2"))

// For comparison, enable overflow errors as well
uc.@Error().@TrapOnOverflow(true);
wl("Test 3 (Overflow with error): ", uc.EvalStr("1e308 * 2"))
```

**Output:**
```
Test 1 (Div by Zero): Division by 0
Test 2 (Overflow): inf
Test 3 (Overflow with error): Floating point overflow
```

---

### Example ID: 406

**Description:** How to enable error raising for invalid operations.

**Code:**
```pseudocode
// By default, invalid operations return 'nan'
wl(uc.EvalStr("sqrt(-1)"))

// Enable error raising for this specific case
uc.@Error().@TrapOnInvalid(true);

// Now, the same operation returns a descriptive error message
wl(uc.EvalStr("sqrt(-1)"))
```

**Output:**
```
nan
Invalid operation
```

---

### Example ID: 407

**Description:** A practical example using an error handler to provide a custom, user-friendly message when an invalid operation occurs.

**Code:**
```pseudocode
[head]
[callback:u MyErrorHandler]
  // Check if the specific 'FloatInvalid' error was raised
  if (uc.@Error().@Code() == ErrorCode::FloatInvalid)
    wl("Error: The calculation resulted in an invalid number (e.g., square root of a negative).")
    // Stop further processing
    uc.@Error().@Response(ErrorHandlerResponse::Abort);
  end if
[/callback]

[body]
// Register the custom error handler
uc.@Error().AddHandler(MyErrorHandler);

// Tell uCalc to raise an error instead of returning 'nan'
uc.@Error().@TrapOnInvalid(true);

// This will now trigger our custom error handler's message
uc.EvalStr("sqrt(-4)");
```

**Output:**
```
Error: The calculation resulted in an invalid number (e.g., square root of a negative).
```

---

### Example ID: 408

**Description:** Internal test verifying the behavior of all `RaiseErrorOn...` flag methods.

**Code:**
```pseudocode
// --- Division by Zero ---
wl(uc.EvalStr("1/0"))
uc.@Error().@TrapOnDivideByZero(true);
wl(uc.EvalStr("1/0"))

// --- Invalid Operation ---
wl(uc.EvalStr("Sqrt(-1)"))
uc.@Error().@TrapOnInvalid(true);
wl(uc.EvalStr("Sqrt(-1)"))

// --- Overflow ---
wl(uc.EvalStr("5*10^308"))
uc.@Error().@TrapOnOverflow(true);
wl(uc.EvalStr("5*10^308"))

// --- Underflow ---
wl(uc.EvalStr("10^-308/10000"))
uc.@Error().@TrapOnUnderflow(true);
wl(uc.EvalStr("10^-308/10000"))
```

**Output:**
```
inf
Division by 0
nan
Invalid operation
inf
Floating point overflow
0
Floating point underflow
```

---

### Example ID: 409

**Description:** How to toggle overflow error reporting on and off.

**Code:**
```pseudocode
// 1. Default behavior: returns 'inf'
wl(uc.EvalStr("1e308 * 10"))

// 2. Enable error raising for overflow
uc.@Error().@TrapOnOverflow(true);
wl(uc.EvalStr("1e308 * 10"))

// 3. Disable it again to revert to default
uc.@Error().@TrapOnOverflow(false);
wl(uc.EvalStr("1e308 * 10"))
```

**Output:**
```
inf
Floating point overflow
inf
```

---

### Example ID: 410

**Description:** A practical example demonstrating all four related floating-point error configuration methods.

**Code:**
```pseudocode
wl("Divide by Zero (Default): ", uc.EvalStr("1/0"))
uc.@Error().@TrapOnDivideByZero(true);
wl("Divide by Zero (Error Enabled): ", uc.EvalStr("1/0"))

wl("")
wl("Invalid Operation (Default): ", uc.EvalStr("Sqrt(-1)"))
uc.@Error().@TrapOnInvalid(true);
wl("Invalid Operation (Error Enabled): ", uc.EvalStr("Sqrt(-1)"))

wl("")
wl("Overflow (Default): ", uc.EvalStr("5*10^308"))
uc.@Error().@TrapOnOverflow(true);
wl("Overflow (Error Enabled): ", uc.EvalStr("5*10^308"))

wl("")
wl("Underflow (Default): ", uc.EvalStr("10^-308/10000"))
uc.@Error().@TrapOnUnderflow(true);
wl("Underflow (Error Enabled): ", uc.EvalStr("10^-308/10000"))
```

**Output:**
```
Divide by Zero (Default): inf
Divide by Zero (Error Enabled): Division by 0

Invalid Operation (Default): nan
Invalid Operation (Error Enabled): Invalid operation

Overflow (Default): inf
Overflow (Error Enabled): Floating point overflow

Underflow (Default): 0
Underflow (Error Enabled): Floating point underflow
```

---

### Example ID: 411

**Description:** Internal Test: An overflow error is intercepted by a custom error handler.

**Code:**
```pseudocode
[head]
[callback:u MyErrorHandler]
    wl("--- Error Handler Caught ---")
    wl("  Code: ", [c](int)[/c][vb]CInt([/vb]uc.@Error().@Code()[vb])[/vb])
    wl("  Message: ", uc.@Error().@Message())
    // Abort is the default response, no need to set it.
[/callback]

[body]
// Register the custom error handler
uc.@Error().AddHandler(MyErrorHandler);

// Configure the engine to raise an error on overflow
uc.@Error().@TrapOnOverflow(true);

// This evaluation will now be intercepted by our handler
wl("Evaluating expression '1e999'...")
uc.EvalStr("1e999"); // This triggers the callback
wl("Evaluation finished.")
```

**Output:**
```
Evaluating expression '1e999'...
--- Error Handler Caught ---
  Code: 4
  Message: Floating point overflow
Evaluation finished.
```

---

### Example ID: 430

**Description:** Retrieves a double-precision value from a pointer, with and without formatting.

**Code:**
```pseudocode
// Define a global format for the 'formattedOutput' parameter
uc.Format("Result = 'Answer: <' + Result + '>'");

// Create a variable and get its memory address
var myDouble = uc.DefineVariable("MyDouble = 123.456");
var ptr = myDouble.ValueAddr();

// 1. Retrieve the value by specifying the data type by name
wl("By Name: ", uc.ValueAt(ptr, "Double"))

// 2. Retrieve the value using the built-in enum
wl("By Enum: ", uc.ValueAt(ptr, BuiltInType::Float_Double))

// 3. Retrieve the value with formatting enabled
wl("Formatted: ", uc.ValueAt(ptr, BuiltInType::Float_Double, true))
```

**Output:**
```
By Name: 123.456
By Enum: 123.456
Formatted: Answer: <123.456>
```

---

### Example ID: 431

**Description:** Demonstrates type punning by interpreting an unsigned byte (`Int8u`) result as a signed byte (`Int8`) to observe how values wrap around.

**Code:**
```pseudocode
// Define a variable 'x' that will be used in our expression
var variableX = uc.DefineVariable("x As Int");

// Parse an expression that will result in an unsigned 8-bit integer (0-255)
var parsedExpr = uc.Parse("x + 125", "Int8u");

wl("x | Int8u (0 to 255) | Int8 (-128 to 127)")
wl("------------------------------------------")

for (int x = 1 to 5)
   variableX.ValueInt32(x);

   // Evaluate the expression to get a pointer to the result
   var resultPtr = parsedExpr.EvaluateVoid();

   // Get the raw unsigned result
   var unsignedResult = uc.ValueAt(resultPtr, "Int8u");

   // Use ValueAt to *re-interpret* the same memory as a signed byte
   var signedResult = uc.ValueAt(resultPtr, "Int8");

   wl(x, " | ", unsignedResult, " | ", signedResult)
end for

// Clean up the created items
parsedExpr.Release();
variableX.Release();
```

**Output:**
```
x | Int8u (0 to 255) | Int8 (-128 to 127)
------------------------------------------
1 | 126 | 126
2 | 127 | 127
3 | 128 | -128
4 | 129 | -127
5 | 130 | -126
```

---

### Example ID: 479

**Description:** Triggering a standard syntax error if the input value is negative.

**Code:**
```pseudocode
[head]
[callback DoublePositive]
  // If input is negative, raise a syntax error.
  if (cb.Arg(1) < 0)
    cb.@Error().Raise(ErrorCode::Syntax_Error);
  end if
  cb.Return(cb.Arg(1) * 2);
[/callback]
[body]
uc.DefineFunction("DoublePositive(x)", DoublePositive);
wl(uc.EvalStr("DoublePositive(10)"))
wl(uc.EvalStr("DoublePositive(-5)"))
```

**Output:**
```
20
Syntax error
```

---

### Example ID: 482

**Description:** A function that unconditionally raises a custom error.

**Code:**
```pseudocode
[head]
[callback:u MyHandler]
    // This handler just logs the error and aborts
    wl("Error Handler Caught: ", uc.@Error().@Message())
[/callback]
[callback MyFunc]
    // This function always fails with a custom message
    cb.@Error().Raise("Validation failed for input.");
[/callback]
[body]
uc.@Error().AddHandler(MyHandler);
uc.DefineFunction("Validate()", MyFunc);
uc.EvalStr("Validate()"); // This call will trigger the error
```

**Output:**
```
Error Handler Caught: Validation failed for input.
```

---

### Example ID: 483

**Description:** Raises an error with a dynamic message if a validation check fails within a callback.

**Code:**
```pseudocode
[head]
[callback ValidateValue]
    var val = cb.Arg(1);
    if (val > 100)
        // The error message includes the problematic value, making it dynamic.
        cb.@Error().Raise("Value exceeds maximum of 100. Got: " + [cpp]to_string((int)val)[/cpp][NotCpp]val.ToString()[/NotCpp]);
    else
        cb.Return(val);
    end if
[/callback]
[body]
uc.DefineFunction("CheckValue(val)", ValidateValue);
wl(uc.EvalStr("CheckValue(50)"))
wl(uc.EvalStr("CheckValue(123)"))
```

**Output:**
```
50
Value exceeds maximum of 100. Got: 123
```

---

### Example ID: 484

**Description:** Internal Test: Demonstrates error recovery by having an error handler resume execution after a custom error is raised.

**Code:**
```pseudocode
[head]
[callback:u RecoveryHandler]
    wl("Handler: Caught '", uc.@Error().@Message(), "'")
    // Attempt to recover by resuming execution.
    uc.@Error().@Response(ErrorHandlerResponse::Resume);
    wl("Handler: Resuming execution...")
[/callback]
[callback RiskyOperation]
    var input = cb.ArgStr(1);
    if (input == "bad")
        cb.@Error().Raise("A recoverable error occurred.");
        // After the error handler resumes, this return value will be used.
 
    else
        cb.ReturnStr("Normal_OK");
    end if
[/callback]
[body]
uc.@Error().AddHandler(RecoveryHandler);
uc.DefineFunction("DoWork(s As String) As String", RiskyOperation);

wl("Result: " + uc.EvalStr("DoWork('good')"))
wl("---")
wl("Result: " + uc.EvalStr("DoWork('bad')"))
```

**Output:**
```
Result: Normal_OK
---
Handler: Caught 'A recoverable error occurred.'
Handler: Resuming execution...
Result: A recoverable error occurred.
```

---

### Example ID: 486

**Description:** Disambiguates which function or operator triggered a shared callback.

**Code:**
```pseudocode
[head]
[callback SharedCallback]
   wl("Callback triggered by: ", cb.@Item().@Name())
[/callback]
[body]
// Define two different symbols that use the same callback
uc.DefineFunction("FuncA(x, y)", SharedCallback);
uc.DefineOperator("{x} OpB {y}", 100, Associativity::LeftToRight, SharedCallback);

// Call both symbols
uc.EvalStr("FuncA(1, 2)");
uc.EvalStr("1 OpB 2");

```

**Output:**
```
Callback triggered by: funca
Callback triggered by: opb
```

---

### Example ID: 530

**Description:** Sets the default data type to `Int32` for implicit variable definitions.

**Code:**
```pseudocode
var intType = uc.DataTypeOf("Int32");
intType.@IsDefault(true);

// Define a variable without specifying a type or initial value.
var myVar = uc.DefineVariable("myVar");

// Check the variable's type.
wl("Default type is now: ", uc.@DefaultDataType().@Name());
wl("myVar's type is: ", myVar.@DataType().@Name());
```

**Output:**
```
Default type is now: int
myVar's type is: int
```

---

### Example ID: 532

**Description:** Internal Test: Verifies the ability to set and unset a data type as the default.

**Code:**
```pseudocode
// Initial state: Double is the default
wl("Double is default: ", bool(uc.DataTypeOf("double").@IsDefault()))
wl("Int64 is default: ", bool(uc.DataTypeOf("int64").@IsDefault()))
wl("Current default: ", uc.@DefaultDataType().@Name())
wl("---")

// Set Int64 as the default
uc.DataTypeOf("int64").@IsDefault(true);
wl("Double is default: ", bool(uc.DataTypeOf("double").@IsDefault()))
wl("Int64 is default: ", bool(uc.DataTypeOf("int64").@IsDefault()))
wl("Current default: ", uc.@DefaultDataType().@Name())
wl("---")

// Revert back to Double by un-setting Int64
uc.DataTypeOf("int64").@IsDefault(false);
wl("Double is default: ", bool(uc.DataTypeOf("double").@IsDefault()))
wl("Int64 is default: ", bool(uc.DataTypeOf("int64").@IsDefault()))
wl("Current default: ", uc.@DefaultDataType().@Name())
```

**Output:**
```
Double is default: True
Int64 is default: False
Current default: double
---
Double is default: False
Int64 is default: True
Current default: int64
---
Double is default: True
Int64 is default: False
Current default: double
```

---

### Example ID: 533

**Description:** How to retrieve the Item from a DataType to access its name.

**Code:**
```pseudocode
var intType = uc.DataTypeOf(BuiltInType::Integer_32);

// Get the Item representation of the DataType
var itemHandle = intType.@Item();

wl("Data Type Name via Item: ", itemHandle.@Name())
```

**Output:**
```
Data Type Name via Item: int
```

---

### Example ID: 535

**Description:** Internal test to verify behavior when retrieving the Item for a non-existent data type.

**Code:**
```pseudocode
// Attempt to get an invalid DataType
var invalidType = uc.DataTypeOf("NoSuchType");

// Get its Item representation
var invalidItem = invalidType.@Item();

// Check its properties
wl("Item Is Found: ", bool([c]![/c][vb]Not [/vb] invalidItem.IsProperty(ItemIs::NotFound)))
wl("Item Name: '", invalidItem.@Name(), "'")
```

**Output:**
```
Item Is Found: False
Item Name: ''
```

---

### Example ID: 539

**Description:** Retrieves and displays the name of a built-in data type.

**Code:**
```pseudocode
var intType = uc.DataTypeOf(BuiltInType::Integer_32);
wl("The canonical name for Integer_32 is: ", intType.@Name())

var strType = uc.DataTypeOf(BuiltInType::String);
wl("The canonical name for String is: ", strType.@Name())
```

**Output:**
```
The canonical name for Integer_32 is: int
The canonical name for String is: string
```

---

### Example ID: 540

**Description:** Introspects the inferred data types of several variables and prints their names.

**Code:**
```pseudocode
// Define variables where the type is inferred from the initial value
uc.DefineVariable("myNumber = 10.5");
uc.DefineVariable("myText = 'hello'");
uc.DefineVariable("myFlag = true");

// Get the item and then its data type name
var item1 = uc.ItemOf("myNumber");
wl("'myNumber' is of type: ", item1.@DataType().@Name())

var item2 = uc.ItemOf("myText");
wl("'myText' is of type: ", item2.@DataType().@Name())

var item3 = uc.ItemOf("myFlag");
wl("'myFlag' is of type: ", item3.@DataType().@Name())
```

**Output:**
```
'myNumber' is of type: double
'myText' is of type: string
'myFlag' is of type: bool
```

---

### Example ID: 560

**Description:** How to retrieve the parent uCalc instance from a DataType object.

**Code:**
```pseudocode
uc.@Description("Main uCalc Instance");

// Get the DataType object for Int32
var intType = uc.DataTypeOf(BuiltInType::Integer_32);

// Use the .uCalc() method to get back to the parent instance and read its description.
wl(intType.@uCalc().@Description())
```

**Output:**
```
Main uCalc Instance
```

---

### Example ID: 562

**Description:** Internal test to confirm instance isolation by proving a DataType is strictly bound to its parent uCalc instance.

**Code:**
```pseudocode
// Create two completely separate uCalc instances.
New(uCalc, uc1)
uc1.DefineVariable("x = 100");

New(uCalc, uc2)
uc2.DefineVariable("x = 200");

// Get the DataType for 'Int' from the *first* instance.
var intType_from_uc1 = uc1.DataTypeOf("Int");

// Use the .uCalc() method to get the parent instance.
// This should be uc1, so evaluating 'x' should yield 100.
var parent = intType_from_uc1.@uCalc();
wl("Parent of intType_from_uc1 evaluates 'x' to: ", parent.Eval("x"))

// Get the DataType for 'Int' from the *second* instance.
var intType_from_uc2 = uc2.DataTypeOf("Int");

// This should be uc2, so evaluating 'x' should yield 200.
parent = intType_from_uc2.@uCalc();
wl("Parent of intType_from_uc2 evaluates 'x' to: ", parent.Eval("x"))
```

**Output:**
```
Parent of intType_from_uc1 evaluates 'x' to: 100
Parent of intType_from_uc2 evaluates 'x' to: 200
```

---

### Example ID: 563

**Description:** Demonstrates the basic creation and immediate evaluation of an expression object.

**Code:**
```pseudocode
// Basic construction and evaluation using the default uCalc instance.
NewUsing(uCalc::Expression, MyExpr("10 * (2 + 3)"))
wl(MyExpr.Evaluate())
End Using
```

**Output:**
```
50
```

---

### Example ID: 564

**Description:** Shows how the constructor's context (default vs. specific instance) affects variable resolution during parsing.

**Code:**
```pseudocode
// Set up two different uCalc contexts with the same variable name 'x'.
uCalc::@DefaultInstance().DefineVariable("x = 1.2");
uc.DefineVariable("x = 10");

wl("--- Testing Expression Contexts ---")

// 1. Expression created in the *default* context uses x = 1.2
NewUsing(uCalc::Expression, exprDefault("x + 5"))
wl("Default context (x=1.2): ", exprDefault.Evaluate())

// 2. Expression created in a *specific* context ('uc') uses x = 10
NewUsing(uCalc::Expression, exprSpecific(uc, "x + 5"))
wl("Specific context (x=10):  ", exprSpecific.Evaluate())

// 3. Create empty, then parse later (uses default context for the Parse call)
NewUsing(uCalc::Expression, exprEmpty)
exprEmpty.Parse("x * 10");
wl("Empty then parsed (x=1.2):", exprEmpty.Evaluate())
End Using
End Using
End Using
```

**Output:**
```
--- Testing Expression Contexts ---
Default context (x=1.2): 6.2
Specific context (x=10):  15
Empty then parsed (x=1.2):12
```

---

### Example ID: 573

**Description:** A simple demonstration of parsing an expression once and then evaluating it.

**Code:**
```pseudocode
// 1. Parse the expression into a reusable object.
var parsedExpr = uc.Parse("100 / 4");

// 2. Evaluate the pre-parsed object.
wl("Result: ", parsedExpr.Evaluate())
```

**Output:**
```
Result: 25
```

---

### Example ID: 574

**Description:** Using the parse-evaluate pattern for high-performance calculations in a loop with a changing variable.

**Code:**
```pseudocode
// Define a variable 'x' that will be updated in the loop.
var variableX = uc.DefineVariable("x");

// Parse the expression just once before the loop begins.
var parsedExpr = uc.Parse("x^2 * 10");

wl("Evaluating 'x^2 * 10' for x = 1 to 5:")
for(double x = 1 to 5)
   variableX.Value(x);
   // Evaluate is very fast as the parsing work is already done.
   wl("x = ", x, ", Result = ", parsedExpr.Evaluate())
end for
```

**Output:**
```
Evaluating 'x^2 * 10' for x = 1 to 5:
x = 1, Result = 10
x = 2, Result = 40
x = 3, Result = 90
x = 4, Result = 160
x = 5, Result = 250
```

---

### Example ID: 601

**Description:** A simple demonstration of parsing an expression and then manually releasing it.

**Code:**
```pseudocode
var expr = uc.Parse("1 + 2");
wl(expr.EvaluateStr())

// Manually release the expression when it's no longer needed.
expr.Release();
```

**Output:**
```
3
```

---

### Example ID: 602

**Description:** Demonstrates the recommended practice of using a scoped block for automatic resource management, preventing memory leaks.

**Code:**
```pseudocode
// A 'NewUsing' block ensures the expression is automatically released at the end of the scope.
// This is the safest pattern to prevent memory leaks.
NewUsing(uCalc::Expression, expr("5 * 10"))
  wl("Result within scope: ", expr.Evaluate())
End Using

// The 'expr' object is now released and its handle is invalid.
wl("Expression has been automatically released.")
```

**Output:**
```
Result within scope: 50
Expression has been automatically released.
```

---

### Example ID: 604

**Description:** Demonstrating that each parsed expression is owned by the uCalc instance that created it.

**Code:**
```pseudocode
// Create two separate uCalc instances
New(uCalc, uc1)
New(uCalc, uc2)

// Parse the same expression string in both instances
var expr1 = uc1.Parse("1 + 1");
var expr2 = uc2.Parse("1 + 1");

// Use the .uCalc() method and MemoryIndex to verify ownership
wl("expr1 belongs to uc1: ", bool(expr1.@uCalc().@MemoryIndex() == uc1.@MemoryIndex()))
wl("expr2 belongs to uc2: ", bool(expr2.@uCalc().@MemoryIndex() == uc2.@MemoryIndex()))
wl("expr1 does not belong to uc2: ", bool(expr1.@uCalc().@MemoryIndex() != uc2.@MemoryIndex()))
```

**Output:**
```
expr1 belongs to uc1: True
expr2 belongs to uc2: True
expr1 does not belong to uc2: True
```

---

### Example ID: 605

**Description:** A practical example of retrieving an expression's parent uCalc instance to dynamically add a formatting rule before evaluation.

**Code:**
```pseudocode
// Practical (Real World)
// Parse an expression
var myExpr = uc.Parse("5 + 4");
wl("Initial evaluation: ", myExpr.Evaluate())

// Retrieve the parent uCalc instance from the expression object
var parentUc = myExpr.@uCalc();

// Use the parent instance to add a new formatting rule
parentUc.Format("Result = 'Answer = ' + Result");

// The new format is now active for this expression's context
wl("Formatted evaluation: ", myExpr.EvaluateStr())
```

**Output:**
```
Initial evaluation: 9
Formatted evaluation: Answer = 9
```

---

### Example ID: 606

**Description:** An internal test verifying that an expression remains tied to its original context, even after the context has been cloned and modified.

**Code:**
```pseudocode
// Internal Test: Context integrity after cloning
New(uCalc, baseUc)
baseUc.DefineVariable("x = 100");

// Clone the base instance and modify the variable in the clone
var clonedUc = baseUc.Clone();
clonedUc.Eval("x = 200");

// Parse an expression in the original base context
var baseExpr = baseUc.Parse("x");

// 1. Verify the expression evaluates using its original context's value
wl("Base expression evaluates to: ", baseExpr.Evaluate())

// 2. Get the parent and verify it is not the cloned instance
wl("Parent is not the clone: ", bool(baseExpr.@uCalc().@MemoryIndex() != clonedUc.M@emoryIndex()))
```

**Output:**
```
Base expression evaluates to: 100
Parent is not the clone: True
```

---

### Example ID: 607

**Description:** Creating a variable in the default instance and retrieving its value.

**Code:**
```pseudocode
NewUsing(uCalc::Item, myVar("Variable: x = 42"))
wl("Created variable '", myVar.@Name(), "' with value: ", myVar.Value())
End Using
```

**Output:**
```
Created variable 'x' with value: 42
```

---

### Example ID: 610

**Description:** Retrieving the element count of an array and the parameter count of a function.

**Code:**
```pseudocode
var MyArray = uc.DefineVariable("MyArray[10] As Int");
var MyFunc = uc.DefineFunction("MyFunc(a, b, c) = a+b+c");

wl("Array element count: ", MyArray.@Count())
wl("Function parameter count: ", MyFunc.@Count())
```

**Output:**
```
Array element count: 10
Function parameter count: 3
```

---

### Example ID: 611

**Description:** Comprehensive demonstration of Count() across arrays, functions with different parameter types, and operators.

**Code:**
```pseudocode
[head]
[callback MyAverage]
var(double, Total) = 0;
for(int x = 1 to cb.ArgCount())
   Total = Total + cb.Arg(x);
end for
cb.Return(Total / cb.ArgCount());
[/callback]
[body]
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");

wl("Elements in array (from initializer): ", MyArrayA.@Count())
wl("Elements in array (from size): ", MyArrayB.@Count())
wl("Parameters in FuncA() (fixed): ", FunctionA.@Count())
wl("Parameters in FuncB() (with optional): ", FunctionB.@Count())
wl("Parameters in FuncC() (variadic): ", FunctionC.@Count())
wl("Parameters in FuncD() (none): ", FunctionD.@Count())
wl("Operands in '!' operator (postfix): ", uc.ItemOf("!").@Count())
wl("Operands in '>' operator (infix): ", uc.ItemOf(">").@Count())
```

**Output:**
```
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
```

---

### Example ID: 613

**Description:** Using Properties with ItemOf to disambiguate between the infix and prefix versions of the '-' operator.

**Code:**
```pseudocode
var infix_minus = uc.ItemOf("-", uCalc::Properties(ItemIs::Infix));
var prefix_minus = uc.ItemOf("-", uCalc::Properties(ItemIs::Prefix));

wl("Operands for infix '-': ", infix_minus.@Count())
wl("Operands for prefix '-': ", prefix_minus.@Count())
```

**Output:**
```
Operands for infix '-': 2
Operands for prefix '-': 1
```

---

### Example ID: 614

**Description:** Demonstrates introspection within a callback, retrieving the parameter count of the calling function.

**Code:**
```pseudocode
[head]
[callback ItemCallback]
   wl("Function '", cb.@Item().@Name(), "' was called.")
   wl("It is defined with ", cb.@Item().@Count(), " parameters.")
[/callback]
[body]
uc.DefineFunction("MyFunc(x, y) As Double", ItemCallback);
uc.EvalStr("MyFunc(1, 2)");
```

**Output:**
```
Function 'myfunc' was called.
It is defined with 2 parameters.
```

---

### Example ID: 616

**Description:** A simple demonstration of retrieving the data type name from a defined variable.

**Code:**
```pseudocode
var myInt = uc.DefineVariable("myInt As Int");
var myIntType = myInt.@DataType();
wl("Variable 'myInt' has type: ", myIntType.@Name())
```

**Output:**
```
Variable 'myInt' has type: int
```

---

### Example ID: 617

**Description:** A practical example showing how to inspect multiple items and display their type properties, distinguishing between simple and compound types.

**Code:**
```pseudocode
var x = uc.DefineVariable("x = 10.5"); // double
var y = uc.DefineVariable("y = 'hello'"); // string
var z = uc.DefineVariable("z As Complex = 1+2*#i"); // complex

wl("Item: ", x.@Name(), ", Type: ", x.@DataType().@Name(), ", Compound: ", bool(x.@DataType().@IsCompound()))
wl("Item: ", y.@Name(), ", Type: ", y.@DataType().@Name(), ", Compound: ", bool(y.@DataType().@IsCompound()))
wl("Item: ", z.@Name(), ", Type: ", z.@DataType().@Name(), ", Compound: ", bool(z.@DataType().@IsCompound()))
```

**Output:**
```
Item: x, Type: double, Compound: False
Item: y, Type: string, Compound: True
Item: z, Type: complex, Compound: True

```

---

### Example ID: 622

**Description:** Attaches and retrieves a simple metadata description from a variable.

**Code:**
```pseudocode
var myVar = uc.DefineVariable("x = 10");
myVar.@Description("Represents the user's current score.");

wl("Variable Name: ", myVar.@Name())
wl("Description: ", myVar.@Description())
```

**Output:**
```
Variable Name: x
Description: Represents the user's current score.
```

---

### Example ID: 625

**Description:** Setting and retrieving a description for a single variable Item.

**Code:**
```pseudocode
var myVar = uc.DefineVariable("x = 10");
myVar.@Description("This is a test variable");

wl("Name: ", myVar.@Name())
wl("Description: ", myVar.@Description())
```

**Output:**
```
Name: x
Description: This is a test variable
```

---

### Example ID: 644

**Description:** A simple demonstration of retrieving the name from a defined variable's Item object.

**Code:**
```pseudocode
// Define a variable and retrieve its name from the Item object.
var myVarItem = uc.DefineVariable("MyCoolVariable = 10");
wl("Item name: ", myVarItem.@Name())
```

**Output:**
```
Item name: mycoolvariable
```

---

### Example ID: 646

**Description:** Internal Test: Verifies correct name retrieval for symbolic operators, internal tokens, and empty items.

**Code:**
```pseudocode
// Internal Test: Verifying names of different item types and edge cases.

// 1. Operator with symbolic name
var plusOp = uc.ItemOf("+", [c]ItemIs::Infix[/c][vb]uCalc.Properties(ItemIs::Infix)[/vb]);
wl("Operator Name: '", plusOp.@Name(), "'")

// 2. Token with internal name
var token = uc.@ExpressionTokens()[TokenType::AlphaNumeric];
wl("Token Name: '", token.@Name(), "'")

// 3. Empty/invalid item
var emptyItem = uc.ItemOf("NonExistentItem");
wl("Empty Item Name: '", emptyItem.@Name(), "'")
wl("Is Found: ", bool([c]![/c]emptyItem.IsProperty(ItemIs::NotFound)[vb]==False[/vb]))
```

**Output:**
```
Operator Name: '+'
Token Name: '_token_alphanumeric'
Empty Item Name: ''
Is Found: False
```

---

### Example ID: 647

**Description:** Introspecting a function or operator from within a callback to retrieve its metadata.

**Code:**
```pseudocode
[head]
[callback ItemCallback]
   wl("Name: " + cb.@Item().@Name())
   wl("Data type: " + cb.@Item().@DataType().@Name())
   wl("Param count: " + to_string(cb.@Item().@Count()))
   w("Procedure type: ")
   if (cb.@Item().IsProperty(ItemIs::Operator))
      wl("Operator")
   else if (cb.@Item().IsProperty(ItemIs::Function))
      wl("Function")
   end if
   wl(cb.@Item().@Text())
   wl(cb.@Item().@Description())
   wl("---")
[/callback]
[body]

uc.DefineFunction("AAA() As Double", ItemCallback).@Description("Does this and that");
uc.DefineFunction("BBB(x, y, z) As String", ItemCallback).@Description("Does something else");
uc.DefineOperator("{x} CCC {y} As Int32", 0, Associativity::LeftToRight, ItemCallback);

uc.EvalStr("AAA()");
uc.EvalStr("BBB(9, 8, 7)");
uc.EvalStr("5 CCC 4");

```

**Output:**
```
Name: aaa
Data type: double
Param count: 0
Procedure type: Function
Function: AAA() As Double
Does this and that
---
Name: bbb
Data type: string
Param count: 3
Procedure type: Function
Function: BBB(x, y, z) As String
Does something else
---
Name: ccc
Data type: int
Param count: 2
Procedure type: Operator
Operator: {x} CCC {y} As Int32

---
```

---

### Example ID: 655

**Description:** Retrieving the precedence levels of built-in arithmetic operators to compare their binding strength.

**Code:**
```pseudocode
var plus_op = uc.ItemOf("+", uCalc::Properties(ItemIs::Infix));
var mul_op = uc.ItemOf("*", uCalc::Properties( ItemIs::Infix));

wl("Precedence of '+': ", plus_op.@Precedence())
wl("Precedence of '*': ", mul_op.@Precedence())
wl("Does '*' bind tighter than '+'? ", bool(mul_op.@Precedence() > plus_op.@Precedence()))
```

**Output:**
```
Precedence of '+': 50
Precedence of '*': 60
Does '*' bind tighter than '+'? True
```

---

### Example ID: 656

**Description:** Defining a new custom operator with a precedence level set relative to an existing operator.

**Code:**
```pseudocode
// Goal: Define a new power operator '**' with higher precedence than multiplication '*'.
var mul_precedence = uc.ItemOf("*", uCalc::Properties(ItemIs::Infix)).@Precedence();

// Set the new operator's precedence to be higher than multiplication.
uc.DefineOperator("{base} ** {exp} = Pow(base, exp)", mul_precedence + 10);

// The new operator should be evaluated before multiplication and addition.
// The expression is equivalent to: 2 + (3 * (2 ** 3)) -> 2 + (3 * 8) -> 2 + 24 -> 26
wl(uc.Eval("2 + 3 * 2 ** 3"))
```

**Output:**
```
26
```

---

### Example ID: 657

**Description:** Internal Test: Demonstrates how changing an operator's precedence at runtime affects the parsing of subsequent expressions.

**Code:**
```pseudocode
// Define '##' with the same precedence as 'And'. 'And' binds tighter than 'Or'.
var and_prec = uc.ItemOf("And", uCalc::Properties(ItemIs::Infix)).@Precedence();
var op_handle = uc.DefineOperator("{a} ## {b} As Boolean = a and b", and_prec);

wl("--- Initial Precedence (like 'And') ---")
// Evaluation is like: true or (false and false) -> true or false -> true
wl(uc.EvalStr("true or false ## 1 == 2"))

// Now, change the precedence to be lower than 'Or'.
var or_prec = uc.ItemOf("Or", uCalc::Properties(ItemIs::Infix)).@Precedence();
op_handle.@Precedence(or_prec - 10);

wl("")
wl("--- Changed Precedence (lower than 'Or') ---")
// Evaluation is like: (true or false) and false -> true and false -> false
wl(uc.EvalStr("true or false ## 1 == 2"))
```

**Output:**
```
--- Initial Precedence (like 'And') ---
true

--- Changed Precedence (lower than 'Or') ---
false
```

---

### Example ID: 673

**Description:** Retrieves the full definition string for a user-defined function.

**Code:**
```pseudocode
uc.DefineFunction("MyFunction(x) = x * 2");
wl(uc.ItemOf("MyFunction").@Text())
```

**Output:**
```
Function: MyFunction(x) = x * 2
```

---

### Example ID: 674

**Description:** Practical: Inspects various properties of an item from within a callback, including its definition text.

**Code:**
```pseudocode
[head]
[callback ItemCallback]
   var itm = cb.@Item();
   wl("Name: ", itm.@Name())
   wl("Data type: ", itm.@DataType().@Name())
   wl("Param count: ", to_string(itm.@Count()))
   w("Procedure type: ")
   if (itm.IsProperty(ItemIs::Operator))
      wl("Operator")
   else if (itm.IsProperty(ItemIs::Function))
      wl("Function")
   end if
   wl("Definition: ", itm.@Text())
   wl("Description: ", itm.@Description())
   wl("---")
[/callback]
[body]
uc.DefineFunction("AAA() As Double", ItemCallback).@Description("Does this and that");
uc.DefineFunction("BBB(x, y, z) As String", ItemCallback).@Description("Does something else");
uc.DefineOperator("{x} CCC {y} As Int32", 55, Associativity::LeftToRight, ItemCallback);

uc.EvalStr("AAA()");
uc.EvalStr("BBB(9, 8, 7)");
uc.EvalStr("5 CCC 4");
```

**Output:**
```
Name: aaa
Data type: double
Param count: 0
Procedure type: Function
Definition: Function: AAA() As Double
Description: Does this and that
---
Name: bbb
Data type: string
Param count: 3
Procedure type: Function
Definition: Function: BBB(x, y, z) As String
Description: Does something else
---
Name: ccc
Data type: int
Param count: 2
Procedure type: Operator
Definition: Operator: {x} CCC {y} As Int32
Description: 
---
```

---

### Example ID: 675

**Description:** Practical: Iterates through all overloads of the '+' operator and displays their unique definition text.

**Code:**
```pseudocode
var PlusOperator = uc.ItemOf("+");

do
   wl("Def: ", PlusOperator.@Text(), " -- Type: ", PlusOperator.@DataType().@Name())
   PlusOperator = PlusOperator.NextOverload();
loop while(PlusOperator.NotEmpty());
```

**Output:**
```
Def: Operator: 70 +{x} -- Type: double
Def: Operator: 50 {x} + {y} -- Type: double
Def: Operator: 50 {x As Int} + {y As Int} As Int -- Type: int
Def: Operator: 50 {x As String} + {y As String} As String -- Type: string
Def: Operator: 50 {x As Complex} + {y As Complex} As Complex -- Type: complex
Def: Operator: 50 {ByHandle x As AnyType Ptr} + {y As Int} As SameTypeAs:0 Ptr -- Type: sametypeas:ptr
Def: Operator: 50 {ByHandle x As AnyType} + {ByHandle y As String} As String -- Type: string
Def: Operator: 50 {ByHandle x As String} + {ByHandle y As AnyType} As String -- Type: string
```

---

### Example ID: 677

**Description:** Demonstrates getting a token's initial type and then changing it using the setter overload.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
var myToken = t.@Tokens().Add("###", TokenType::Generic);
w("Initial Type: ")
wl(bool(myToken.@TypeOfToken() == TokenType::Generic))

// Change the type
myToken.@TypeOfToken(TokenType::Reducible);
w("New Type is Reducible: ")
wl(bool(myToken.@TypeOfToken() == TokenType::Reducible))
End Using
```

**Output:**
```
Initial Type: True
New Type is Reducible: True
```

---

### Example ID: 678

**Description:** Practical: Re-categorizes the newline token as whitespace to allow a pattern to match across multiple lines, a common requirement for parsing HTML or XML.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
var source = [verbatim]<data>
  content spans
  multiple lines
</data>[/verbatim];
t.FromTo("<data>{body}</data>", "Body: [{body}]");

wl("--- Default (Newline is a Separator) ---")
// This fails because {body} stops at the first newline
wl(t.Transform(source).@Text())
wl("")

wl("--- Modified (Newline is Whitespace) ---")
// Find the newline token and change its type
var newlineToken = t.@Tokens()["_token_newline"];
newlineToken.@TypeOfToken(TokenType::Whitespace);
// Now the transform succeeds
wl(t.Transform(source).@Text())
End Using
```

**Output:**
```
--- Default (Newline is a Separator) ---
<data>
  content spans
  multiple lines
</data>

--- Modified (Newline is Whitespace) ---
Body: [content spans
  multiple lines]
```

---

### Example ID: 679

**Description:** Internal Test: Changes a token's type and then reverts it to ensure the state is managed correctly.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
var alphaToken = t.@Tokens()["_token_alphanumeric"];

wl("1. Initial Type is Alphanumeric: ", bool(alphaToken.@TypeOfToken() == TokenType::AlphaNumeric))

// Change it to a literal
alphaToken.@TypeOfToken(TokenType::Literal);
wl("2. Type is now Literal: ", bool(alphaToken.@TypeOfToken() == TokenType::Literal))
wl("3. Type is no longer Alphanumeric: ", bool(alphaToken.@TypeOfToken() != TokenType::AlphaNumeric))

// Change it back
alphaToken.@TypeOfToken(TokenType::AlphaNumeric);
wl("4. Reverted Type is Alphanumeric: ", bool(alphaToken.@TypeOfToken() == TokenType::AlphaNumeric))
End Using
```

**Output:**
```
1. Initial Type is Alphanumeric: True
2. Type is now Literal: True
3. Type is no longer Alphanumeric: True
4. Reverted Type is Alphanumeric: True
```

---

### Example ID: 680

**Description:** Basic round-trip from an item back to its parent instance.

**Code:**
```pseudocode
New(uCalc, myInstance)
// Define a variable and get its Item object
var v = myInstance.DefineVariable("v = 10");

// Use the item to get back to its parent uCalc instance
var parentInstance = v.@uCalc();

// Perform another evaluation in the same context
wl(parentInstance.EvalStr("v + 5"))
```

**Output:**
```
15
```

---

### Example ID: 681

**Description:** A practical example showing how to manage two separate uCalc instances with conflicting variable names.

**Code:**
```pseudocode
// Create two independent uCalc instances
New(uCalc, uc1)
New(uCalc, uc2)

// Define a variable 'x' in each instance with a different value
var itemX1 = uc1.DefineVariable("x = 100");
var itemX2 = uc2.DefineVariable("x = 200");

// Use the item to get its parent context and evaluate 'x * 2'
// This correctly uses uc1's context where x is 100.
wl("Context 1: ", itemX1.@uCalc().Eval("x * 2"));

// This correctly uses uc2's context where x is 200.
wl("Context 2: ", itemX2.@uCalc().Eval("x * 2"))

// Clean up the instances
uc1.Release();
uc2.Release();
```

**Output:**
```
Context 1: 200
Context 2: 400
```

---

### Example ID: 785

**Description:** How to count all alphanumeric words in a sentence.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("There are five words here.");

// Define a pattern to find any alphanumeric word
t.Pattern("{@Alpha}");
t.Find();

wl("Total words found: ", t.@Matches().Count())
```

**Output:**
```
Total words found: 5
```

---

### Example ID: 786

**Description:** A practical example showing the difference between counting all matches and counting matches for a specific rule.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("<h1>Header</h1><p>Paragraph 1.</p><p>Paragraph 2.</p>");

// Define rules for different tags
var h1Rule = t.Pattern("<h1>{text}</h1>");
var pRule = t.Pattern("<p>{text}</p>");
t.Find();

// Get the total count of all matches from all rules
wl("Total matches (all rules): ", t.@Matches().Count())

// Get the count for only the paragraph rule
wl("Paragraph matches only: ", pRule.@Matches().Count())
```

**Output:**
```
Total matches (all rules): 3
Paragraph matches only: 2
```

---

### Example ID: 787

**Description:** Internal Test: Verifies how filtering the matches collection affects the count.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("ID:100, Name:Admin, ID:200");

// Define two rules, but only one is marked as 'focusable'
var idRule = t.Pattern("ID:{@Number}").SetFocusable(true);
var nameRule = t.Pattern("Name:{@Alpha}").SetFocusable(false);
t.Find();

// The total count includes all matches regardless of properties
wl("Total matches found: ", t.@Matches().Count())

// The count changes when we filter the list to only include focusable matches
var focusableMatches = t.GetMatches(MatchesOption::FocusableOnly);
wl("Focusable matches count: ", focusableMatches.Count())
```

**Output:**
```
Total matches found: 3
Focusable matches count: 2
```

---

### Example ID: 788

**Description:** Returns Start and End positions of Transformer matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<br><h1>First</h1>Blah Blah<br>Testing<br><h2>Second</h2>");
//         ^             ^                       ^              ^
//     012345678901234567890123456789012345678901234567890123456789
//     0         10        20        30        40        50
// Carrets (^) point to Start and End locations of the matches

wl(t.@Text())
wl("")

t.Pattern("<{tag}>{etc}</{tag}>");
t.Find();
var Matches = t.@Matches();

wl(Matches[0].@Text())
wl("Start pos: ", Matches[0].@StartPosition())
wl("End pos: ", Matches[0].@EndPosition())
wl("Length: ", Matches[0].@Length())
wl("")

wl(Matches[1].@Text())
wl("Start pos: ", Matches[1].@StartPosition())
wl("End pos: ", Matches[1].@EndPosition())
wl("Length: ", Matches[1].@Length())
```

**Output:**
```
<br><h1>First</h1>Blah Blah<br>Testing<br><h2>Second</h2>

<h1>First</h1>
Start pos: 4
End pos: 18
Length: 14

<h2>Second</h2>
Start pos: 42
End pos: 57
Length: 15
```

---

### Example ID: 789

**Description:** Optional part in the Transformer

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("a [{txt}] b", "a, {txt:{txt}, }b");
wl(t.Transform("a b"))
wl(t.Transform("a x b"))


```

**Output:**
```
a, b
a, x, b
```

---

### Example ID: 790

**Description:** A simple optional word.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("This is a [very] important test", "MATCHED");

// Matches with the optional word
wl(t.Transform("This is a very important test"))

// Also matches without the optional word
wl(t.Transform("This is a important test"))
```

**Output:**
```
MATCHED
MATCHED
```

---

### Example ID: 791

**Description:** A practical example using a fallback content block to provide a default status for log entries.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Pattern: Match "Log:", an optional level (Warning or Error), and the message.
// Replacement: Use `{!level:OK}` to insert 'OK' if no level was captured.
t.FromTo("Log: [{level: Warning | Error}] {msg}", "Status: {!level:OK}{level} | Message: {msg}");

wl(t.Transform("Log: This is a standard entry"))
wl(t.Transform("Log: Warning A potential issue was found"))
wl(t.Transform("Log: Error System failure detected"))
```

**Output:**
```
Status: OK | Message: This is a standard entry
Status: Warning | Message: A potential issue was found
Status: Error | Message: System failure detected
```

---

### Example ID: 792

**Description:** A practical example of parsing names with an optional middle name, using a positive conditional block.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Pattern: Capture first, optional middle, and last names.
// Replacement: The block `{middle: {middle}}` ensures a leading space is only added if a middle name exists.
t.FromTo("Name: {first:1} [{middle:1}] {last:1}", 
         "User: {last}, {first}{middle: {middle}}");

wl(t.Transform("Name: John Doe"))
wl(t.Transform("Name: John Quincy Adams"))
```

**Output:**
```
User: Doe, John
User: Adams, John Quincy
```

---

### Example ID: 794

**Description:** Matching one of several status keywords.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("Status: { OK | Error | Pending }", "Found Valid Status");

wl(t.Transform("Status: OK"))
wl(t.Transform("Status: Error"))
wl(t.Transform("Status: Fail"))
```

**Output:**
```
Found Valid Status
Found Valid Status
Status: Fail
```

---

### Example ID: 795

**Description:** Normalizing various boolean representations to a standard format.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Normalize 'true-like' and 'false-like' values
t.FromTo("{ True | Yes | On }", "TRUE");
t.FromTo("{ False | No | Off }", "FALSE");

wl(t.Transform("System is On and Power is False"))
wl(t.Transform("Access: Yes, Admin: No"))
```

**Output:**
```
System is TRUE and Power is FALSE
Access: TRUE, Admin: FALSE
```

---

### Example ID: 801

**Description:** Lists the names of all standard data types registered in the current uCalc instance.

**Code:**
```pseudocode
foreach(var Item in uc.@DataTypes())
   wl(Item.@Name())
end foreach
```

**Output:**
```
anytype
bool
bool
int8u
complex
double
single
int
int16
int16u
int
int32u
int64
int64u
int8
int8u
int
omnitype
pointer
sametypeas
single
size_t
string
void
```

---

### Example ID: 802

**Description:** GetMessage

**Code:**
```pseudocode
wl(uc.@Error().GetMessage(ErrorCode::Syntax_Error))
wl(uc.@Error().GetMessage(ErrorCode::FloatOverflow))
```

**Output:**
```
Syntax error
Floating point overflow
```

---

### Example ID: 803

**Description:** Demonstrates implicit parsing on assignment and implicit evaluation when writing to the console.

**Code:**
```pseudocode
New(uCalc::Expression, expr("3+4"))
wl("Initial: ", expr) // Implicit EvaluateStr

expr = "20+100"; // Implicit Parse
wl("Reassigned: ", expr) // Implicit EvaluateStr
```

**Output:**
```
Initial: 7
Reassigned: 120
```

---

### Example ID: 804

**Description:** Shows how implicit conversions simplify using uCalc objects for text manipulation.

**Code:**
```pseudocode
[vb]New(uCalc::Transformer, t)
New(uCalc::String, s)[/vb][c]uCalc::Transformer t;
uCalc::String s;[/c]

// Implicitly set the Text property
t = "Source text with foo.";
s = "bar";

// Use the objects in a standard way
t.FromTo("foo", s.@Text());
t.Transform();

// Implicitly get the Text property
wl(t)
```

**Output:**
```
Source text with bar.
```

---

### Example ID: 805

**Description:** Internal Test: Verifies error handling with implicit parsing and evaluation.

**Code:**
```pseudocode
New(uCalc::Expression, expr)

// Implicitly parse an invalid expression. This sets an error state.
expr = "5 * (10 +";

// Implicit EvaluateStr should not throw but return the error message.
wl("Error Message: ", expr)

// Verify the error code is set.
wl("Error Code: ", [c](int)[/c][vb]CInt([/vb]expr.@uCalc().@Error().@Code()[vb])[/vb])

// Now, assign a valid expression.
expr = "10 + 20";

// The new assignment should clear the error state.
wl("Valid Result: ", expr)
wl("Error Code after success: ", [c](int)[/c][vb]CInt([/vb]expr.@uCalc().@Error().@Code()[vb])[/vb])
```

**Output:**
```
Error Message: Bracket delimiter error
Error Code: 265
Valid Result: 30
Error Code after success: 0
```

---

### Example ID: 806

**Description:** Demonstrates the core C# idioms: `using` for lifetime management, property syntax for setters/getters, and implicit string conversions.

**Code:**
```pseudocode
[CS]
// 1. Automatic resource management with 'using'
using (var u = new uCalc()) {
    // 2. Property syntax for setting the description
    u.Description = "My C# uCalc instance";
    wl("Description: ", u.Description)

    // 3. Implicit string conversion for Transformer.Text
    New(uCalc::Transformer, t) 
    t.Text = "Hello World"; // Standard assignment
    t = "Hello Again";    // Implicit conversion assignment
    wl("Transformer Text: ", t.Text)

}
[/CS]
[NotCS]
// This example is meant for C# only
wl("Description: My C# uCalc instance")
wl("Transformer Text: Hello Again")
[/NotCS]
```

**Output:**
```
Description: My C# uCalc instance
Transformer Text: Hello Again
```

---

### Example ID: 812

**Description:** Demonstrates automatic resource management in C++ using RAII and the Owned() method.

**Code:**
```pseudocode
[cpp]
// Create a uCalc object on the stack.
New(uCalc, myCalc)
// Flag it as 'owned' to enable automatic cleanup.
myCalc.Owned();

myCalc.DefineVariable("x=10");
w("Evaluating in scope: ", myCalc.Eval("x*2"))

// When 'myCalc' goes out of scope at the end of the block,
// its destructor is called, which automatically calls Release().
[/cpp]
[NotCpp]
// This example is meant only for C++
w("Evaluating in scope: 20")
[/NotCpp]
```

**Output:**
```
Evaluating in scope: 20
```

---

### Example ID: 815

**Description:** Core VB.NET idioms: `Using` for lifetime management, property syntax, and implicit string conversions.

**Code:**
```pseudocode
[VB]
' 1. Automatic resource management with 'Using'
Using u = New uCalc()
    ' 2. Property syntax for setting the description
    u.Description = "My VB.NET uCalc instance"
    wl("Description: ", u.Description)

    ' 3. Implicit string conversion for Transformer.Text
    New(uCalc::Transformer, t)
    t.Text = "Hello World" ' Standard assignment
    t = "Hello Again"    ' Implicit conversion assignment
    wl("Transformer Text: ", t.Text)
    wl("Transformer Text: ", t)
End Using
[/VB]
[NotVB]
// This example is meant for VB.NET only
wl("Description: My VB.NET uCalc instance")
wl("Transformer Text: Hello Again")
wl("Transformer Text: Hello Again")
[/NotVB]
```

**Output:**
```
Description: My VB.NET uCalc instance
Transformer Text: Hello Again
Transformer Text: Hello Again
```

---

### Example ID: 824

**Description:** A practical example that iterates through all words in a sentence to find the one with the greatest length.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("Find the longest word in this sentence.");
t.Pattern("{@Alpha}"); // Match all words
t.Find();

var(int, maxLength) = 0;
var(string, longestWord) = "";
foreach(var match in t.@Matches())
    if (match.@Length() > maxLength)
        maxLength = match.@Length();
        longestWord = match.@Text();
    end if
end foreach

wl("Longest word is '", longestWord, "' with length: ", maxLength)
```

**Output:**
```
Longest word is 'sentence' with length: 8
```

---

### Example ID: 826

**Description:** Finds a single match and retrieves the name of the rule that generated it.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var ruleA = t.FromTo("apple", "fruit");
t.@Text("an apple a day");
t.Find();

var firstMatch = t.@Matches()[0];
var generatingRule = firstMatch.@Rule();

w("Match text: '", firstMatch.@Text(), "' was found by rule: '", generatingRule.@Name(), "'")
```

**Output:**
```
Match text: 'apple' was found by rule: 'apple'
```

---

### Example ID: 827

**Description:** Assigns descriptive text to multiple rules and uses the `Rule` property to identify which rule generated each match.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b><p>My paragraph</p>");

var AnyOtherTag = t.Pattern("<{tag}>{text}</{tag}>").SetDescription("other kind of tag");
var BoldTag = t.Pattern("<b>{text}</b>").SetDescription("bold tag");
var H3Tag = t.Pattern("<h3>{text}</h3>").SetDescription("h3 tag");
t.Find();

foreach(var match in t.@Matches())
   wl(match.@Text() + "   Description: " + match.@Rule().@Description())
end foreach
```

**Output:**
```
<h3>Title</h3>   Description: h3 tag
<b>Bold statement</b>   Description: bold tag
<h3>Title B</h3>   Description: h3 tag
<b>Other text</b>   Description: bold tag
<p>My paragraph</p>   Description: other kind of tag
```

---

### Example ID: 828

**Description:** Internal Test: Uses integer tags to programmatically categorize matches and process them differently in a loop.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Text("Log: INFO message. Log: ERROR alert. Log: INFO another message.");

var infoRule = t.Pattern("Log: INFO {msg}.").SetTag(1); // Tag 1 for INFO
var errorRule = t.Pattern("Log: ERROR {msg}.").SetTag(99); // Tag 99 for ERROR

t.Find();

foreach(var match in t.@Matches())
    var ruleTag = match.@Rule().@Tag();
    if (ruleTag == 1)
        wl("Found informational log: ", match.@Text())
    end if
    if (ruleTag == 99)
        wl("!!! Found CRITICAL error: ", match.@Text(), " !!!")
    end if
end foreach
```

**Output:**
```
Found informational log: Log: INFO message.
!!! Found CRITICAL error: Log: ERROR alert. !!!
Found informational log: Log: INFO another message.
```

---

### Example ID: 829

**Description:** A basic example to get the starting index of a single word.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Text("Hello World");
t.Pattern("World");
t.Find();

var matches = t.@Matches();
wl("Match found at position: ", matches[0].@StartPosition())
```

**Output:**
```
Match found at position: 6
```

---

### Example ID: 830

**Description:** Parsing log entries to create a map of error locations within the text.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Text("[INFO] System boot. [ERROR] Connection failed. [INFO] Retrying...");
t.Pattern("'['ERROR']' {msg}.");
t.Find();

wl("Found ", t.@Matches().Count(), " error(s):")
foreach(var match in t.@Matches())
  wl("- '", match.@Text(), "' starts at index ", match.@StartPosition())
end foreach
```

**Output:**
```
Found 1 error(s):
- '[ERROR] Connection failed.' starts at index 20
```

---

### Example ID: 831

**Description:** Internal Test: Verifies that StartPosition is correct for multiple, non-contiguous matches.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("a b c a d e a f g");
//        ^       ^       ^
// Pos:   0       6       12
t.Pattern("a");
t.Find();

var matches = t.@Matches();
wl("Match 1 Start: ", matches[0].@StartPosition()) // Should be 0
wl("Match 2 Start: ", matches[1].@StartPosition()) // Should be 6
wl("Match 3 Start: ", matches[2].@StartPosition()) // Should be 12
```

**Output:**
```
Match 1 Start: 0
Match 2 Start: 6
Match 3 Start: 12
```

---

### Example ID: 832

**Description:** How to get the text of the first match found.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("The quick brown fox");
t.Pattern("brown");
t.Find();

// Get the collection of matches
var matches = t.@Matches();

// Check if any matches were found
    // Get the first match object and retrieve its text
    var firstMatch = matches[0];
    wl("Found match: '", firstMatch.@Text(), "'")

```

**Output:**
```
Found match: 'brown'
```

---

### Example ID: 833

**Description:** A practical example that finds all HTML-style tags and prints the text of each one.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<h1>Title</h1><p>Text</p>");

// Pattern to find any tag and its content
t.Pattern("<{tag}>{content}</{tag}>");
t.Find();

var allMatches = t.@Matches();
wl("Found ", allMatches.Count(), " matches:")

// Loop through each Match object and print its Text
foreach (var match in allMatches)
    wl(" - ", match.@Text())
end foreach
```

**Output:**
```
Found 2 matches:
 - <h1>Title</h1>
 - <p>Text</p>
```

---

### Example ID: 837

**Description:** Retrieving the text of the first match found in a simple search.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("The price is $19.99 today.");
t.Pattern("{@Number}"); // Find the first number
t.Find();

// Get the collection of matches
var matches = t.@Matches();

// Check if any match was found and get its text
if (matches.Count() > 0)
    wl(matches[0].@Text())
end if
```

**Output:**
```
19.99
```

---

### Example ID: 838

**Description:** Iterating through multiple HTML tag matches and printing the text of each one.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<p>First paragraph.</p> <div>Content</div>");

// Pattern to find any simple HTML-like tag
t.Pattern("<{tag}>{content}</{tag}>");
t.Find();

var matches = t.@Matches();
wl("Found ", matches.Count(), " tags:")
foreach (var match in t.@Matches())
    wl("- ", match.@Text())
end foreach
```

**Output:**
```
Found 2 tags:
- <p>First paragraph.</p>
- <div>Content</div>
```

---

### Example ID: 843

**Description:** A simple lookup to find the index of the second occurrence of the word 'is'.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("This is a test. It is simple.");
t.Pattern("{@Alpha}");
t.Find();

// The second 'is' starts at character position 19
var index = t.@Matches().IndexOf(19);

wl("The match at character 19 is at index: ", index) 
wl("Match content: '", t.@Matches()[index].@Text(), "'")
```

**Output:**
```
The match at character 19 is at index: 5
Match content: 'is'
```

---

### Example ID: 844

**Description:** Finds the global index of a match that was retrieved from a rule-specific match list.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var log = "INFO: Task started. ERROR: Connection failed. INFO: Task finished.";


var infoRule = t.Pattern("INFO: {msg}.");
var errorRule = t.Pattern("ERROR: {msg}.");
t.@Text(log);
t.Find();

// Get the first match specific to the error rule
var firstErrorMatch = errorRule.@Matches()[0];
wl("First error match text: '", firstErrorMatch.@Text(), "'")

// Now, find its index within the global list of all matches
var globalIndex = t.@Matches().IndexOf(firstErrorMatch.@StartPosition());
wl("The first error is the match at global index: ", globalIndex)

// Verify by printing the match from the global list
wl("Global match at that index: '", t.@Matches()[globalIndex].@Text(), "'")
```

**Output:**
```
First error match text: 'ERROR: Connection failed.'
The first error is the match at global index: 1
Global match at that index: 'ERROR: Connection failed.'
```

---

### Example ID: 849

**Description:** A simple demonstration of adding a fixed offset to a match's coordinates.

**Code:**
```pseudocode
var t = uc.NewTransformer().SetText("The quick brown fox jumps over.");
t.Pattern("fox");
t.Find();

var matches = t.@Matches();
wl("Original Start Position: ", matches[0].@StartPosition())

// Add an offset of 100 to all match positions
matches.ApplyOffset(100);

wl("New Start Position: ", matches[0].@StartPosition())
```

**Output:**
```
Original Start Position: 16
New Start Position: 116
```

---

### Example ID: 850

**Description:** A practical example showing how to remap a match found in a substring back to the global coordinates of the original document.

**Code:**
```pseudocode
[c]string document[/c][vb]Dim Document As String[/vb] = "HEADER::BEGIN[data to find]END::FOOTER";

// 1. Isolate the content block we want to search in.
// Assume the block we care about is between BEGIN and END.
var startIndex = document.[cpp]find[/cpp][NotCpp]IndexOf[/NotCpp]("BEGIN[") + 6;
var endIndex = document.[cpp]find[/cpp][NotCpp]IndexOf[/NotCpp]("]END");
var contentLength = endIndex - startIndex;
var contentBlock = document.[cpp]substr[/cpp][NotCpp]Substring[/NotCpp](startIndex, contentLength);
wl("Searching within substring: '", contentBlock, "'")

// 2. Perform a find operation on just that substring.
var t = uc.NewTransformer().SetText(contentBlock);
t.Pattern("find");
t.Find();
var matches = t.@Matches();

wl("Local match StartPosition: ", matches[0].@StartPosition()) // Relative to 'contentBlock'

// 3. Apply the offset to remap to the global 'document' coordinate space.
matches.ApplyOffset(startIndex);

wl("Global match StartPosition: ", matches[0].@StartPosition())
```

**Output:**
```
Searching within substring: 'data to find'
Local match StartPosition: 8
Global match StartPosition: 22
```

---

### Example ID: 853

**Description:** Practical: Re-filters a result set to show only 'focusable' matches without re-running the search.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("ID:100, Name:Admin, ID:200");

// Define two rules, but only one is marked as 'focusable'
var idRule = t.Pattern("ID:{@Number}").SetFocusable(true);
var nameRule = t.Pattern("Name:{@Alpha}").SetFocusable(false);
t.Find();

var matches = t.GetMatches(MatchesOption::All);
wl("--- All Matches ---")
wl("Count: ", matches.Count())
wl(matches.@Text())

// Now, re-filter the same results to get only the focusable ones
matches.Reset(MatchesOption::FocusableOnly);
wl("")
wl("--- Focusable Matches Only ---")
wl("Count: ", matches.Count())
wl(matches.@Text())
```

**Output:**
```
--- All Matches ---
Count: 3
ID:100
Name:Admin
ID:200

--- Focusable Matches Only ---
Count: 2
ID:100
ID:200
```

---

### Example ID: 855

**Description:** Filters matches by rule; FilterByRule, Matches.Str, Matches.Count

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b><p>My paragraph</p>");

var AnyOtherTag = t.Pattern("<{tag}>{text}</{tag}>");
var BoldTag = t.Pattern("<b>{text}</b>");
var H3Tag = t.Pattern("<h3>{text}</h3>");
t.Find();

wl("All matches -- count = ", t.@Matches().Count())
wl("----------------------")
wl(t.@Matches().@Text())
wl("")

wl("Only BoldTag matches -- count = ", BoldTag.@Matches().Count())
wl("-------------------------------")
wl(BoldTag.@Matches().@Text())
wl("")

wl("Only H3Tag matches -- count = ", H3Tag.@Matches().Count())
wl("-----------------------------")
wl(H3Tag.@Matches().@Text())
```

**Output:**
```
All matches -- count = 5
----------------------
<h3>Title</h3>
<b>Bold statement</b>
<h3>Title B</h3>
<b>Other text</b>
<p>My paragraph</p>

Only BoldTag matches -- count = 2
-------------------------------
<b>Bold statement</b>
<b>Other text</b>

Only H3Tag matches -- count = 2
-----------------------------
<h3>Title</h3>
<h3>Title B</h3>
```

---

### Example ID: 859

**Description:** How to retrieve the parent uCalc instance from a Matches object and verify its identity.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("some text");
t.Pattern("some");
t.Find();
var m = t.@Matches();

// Get the parent uCalc instance from the Matches collection
var parent_uc = m.@uCalc();

// Verify they are the same instance using their MemoryIndex
wl(bool(parent_uc.@MemoryIndex() == uc.@MemoryIndex()))
```

**Output:**
```
True
```

---

### Example ID: 860

**Description:** Demonstrates context isolation by retrieving the parent uCalc instance from a Matches object and evaluating an expression that only exists in that parent's context.

**Code:**
```pseudocode
New(uCalc, uc1)
uc1.DefineVariable("val = 100");

New(uCalc, uc2)
uc2.DefineVariable("val = 200");

// Create the transformer in uc1's context
var t = uc1.NewTransformer();
t.@Text("data");
t.Pattern("data");
t.Find();

var m = t.@Matches();
var parent_uc = m.@uCalc();

wl("Parent has value: ", parent_uc.Eval("val"))
wl("Is parent uc1? ", bool(parent_uc.@MemoryIndex() == uc1.@MemoryIndex()))
wl("Is parent uc2? ", bool(parent_uc.@MemoryIndex() == uc2.@MemoryIndex()))
```

**Output:**
```
Parent has value: 100
Is parent uc1? True
Is parent uc2? False
```

---

### Example ID: 861

**Description:** Internal Test: Verifies that the parent uCalc instance can be retrieved even from an empty Matches collection.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// NOTE: We do NOT call t.Find(), so the matches collection is empty.

var m = t.@Matches();

wl("Match count: ", m.Count())

// Even with no matches, the parent context should be accessible
var parent_uc = m.@uCalc();

wl("Parent uCalc is valid: ", bool(parent_uc.@MemoryIndex() == uc.@MemoryIndex()))
```

**Output:**
```
Match count: 0
Parent uCalc is valid: True
```

---

### Example ID: 862

**Description:** Demonstrates the basic toggle functionality of the Active property.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var(string, UserText) = "The cat saw another cat.";
t.@Text(UserText);

// Define a rule and hold its handle
var catRule = t.FromTo("cat", "dog");

w("1. Rule Active (Default): ")
wl(t.Transform())

// Deactivate the rule
catRule.@Active(false);

// Re-run the transform to see the change
w("2. Rule Inactive: ")
t.@Text(UserText);
wl(t.Transform())

// Reactivate the rule
catRule.@Active(true);
w("3. Rule Reactivated: ")
wl(t.Transform())
```

**Output:**
```
1. Rule Active (Default): The dog saw another dog.
2. Rule Inactive: The cat saw another cat.
3. Rule Reactivated: The dog saw another dog.
```

---

### Example ID: 871

**Description:** How to set a description on a rule and then retrieve it.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var myRule = t.FromTo("Hello", "Hi");
myRule.@Description("Simple greeting replacement");

wl("Rule Pattern: ", myRule.@Pattern())
w("Rule Description: ", myRule.@Description())
```

**Output:**
```
Rule Pattern: Hello
Rule Description: Simple greeting replacement
```

---

### Example ID: 874

**Description:** A basic demonstration of toggling the Focusable flag to filter a list of matches.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("A B C");

var ruleA = t.Pattern("A").SetFocusable(true);
var ruleB = t.Pattern("B").SetFocusable(true);
var ruleC = t.Pattern("C").SetFocusable(false); // C is not focusable
t.Find();

wl("--- All Matches ---")
wl(t.GetMatches(MatchesOption::All).@Text())

w("--- Focusable Matches ---")
// This list will exclude the match for 'C'.
wl(t.GetMatches(MatchesOption::FocusableOnly).@Text())
```

**Output:**
```
--- All Matches ---
A
B
C
--- Focusable Matches ---A
B
```

---

### Example ID: 876

**Description:** The difference between counting all matches versus matches for a specific rule.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("A B C A B C");

var ruleA = t.Pattern("A");
var ruleB = t.Pattern("B");

t.Find();

wl("Total matches (all rules): ", t.@Matches().Count())
wl("Matches for Rule A only: ", ruleA.@Matches().Count())
wl("Matches for Rule B only: ", ruleB.@Matches().Count())
```

**Output:**
```
Total matches (all rules): 4
Matches for Rule A only: 2
Matches for Rule B only: 2
```

---

### Example ID: 877

**Description:** A practical example using `MatchesOption::FocusableOnly` to retrieve results only from rules marked as focusable.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("ID:100, Name:Admin, ID:200");

// Mark 'ID' rules as focusable, but 'Name' rules as secondary.
var idRule = t.Pattern("ID:{@Number}").SetFocusable(true);
var nameRule = t.Pattern("Name:{@Alpha}").SetFocusable(false);
t.Find();

// Get the matches for the 'idRule' specifically, filtered to only focusable results.
var focusableIdMatches = idRule.GetMatches(MatchesOption::FocusableOnly);

wl("Focusable 'ID' matches found: ", focusableIdMatches.Count())
wl(focusableIdMatches.@Text())
```

**Output:**
```
Focusable 'ID' matches found: 2
ID:100
ID:200
```

---

### Example ID: 879

**Description:** Demonstrates how `GlobalMaximum` invalidates a search if a rule matches too many times.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var rule = t.FromTo("ERROR", "[ERR]");
rule.@GlobalMaximum(2);

// This input has 3 matches, which exceeds the maximum of 2.
var(string, input1) = "ERROR 1, ERROR 2, ERROR 3";
t.Transform(input1);
wl("Input 1 Match Count: ", t.@Matches().Count()) // Expect 0

// This input has 2 matches, which is within the limit.
var(string, input2) = "ERROR 1, ERROR 2";
t.Transform(input2);
wl("Input 2 Match Count: ", t.@Matches().Count()) // Expect 2
wl(t)
```

**Output:**
```
Input 1 Match Count: 0
Input 2 Match Count: 2
[ERR] 1, [ERR] 2
```

---

### Example ID: 881

**Description:** Internal Test: Compares the behavior of `Maximum` and `GlobalMaximum` at different thresholds to validate their distinct scopes of invalidation.

**Code:**
```pseudocode
var FruitsXML = 
[verbatim]
<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' />
</Fruits>
[/verbatim];

New(uCalc::Transformer, t)
var fruitsTagRule = t.FromTo("<Fruits>", "List of fruits");
var fruitRule = t.FromTo("CommonName={@string:name}", "- {name}");

wl("--- Using Maximum (Rule-Level) ---")
fruitRule.@Maximum(3); // Rule fails if more than 3 fruits are found.
t.Filter(FruitsXML);
wl("Match count when fruit rule fails: ", t.@Matches().Count()) // The 'fruitsTagRule' still matches.
wl(t.@Matches().@Text())

wl("")
wl("--- Using GlobalMaximum (Transformer-Level) ---")
fruitRule.@Maximum(-1); // Reset local maximum
fruitRule.@GlobalMaximum(3); // Transformer fails if more than 3 fruits are found.
t.Filter(FruitsXML);
wl("Match count when global rule fails: ", t.@Matches().Count()) // All matches are invalidated.
wl(t.@Matches().@Text())
```

**Output:**
```
--- Using Maximum (Rule-Level) ---
Match count when fruit rule fails: 1
List of fruits

--- Using GlobalMaximum (Transformer-Level) ---
Match count when global rule fails: 0

```

---

### Example ID: 882

**Description:** Demonstrates the pass/fail behavior of GlobalMinimum. If the rule doesn't find at least 3 'a's, the entire transform fails.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var ruleA = t.FromTo("a", "A");
var ruleB = t.FromTo("b", "B");
ruleA.@GlobalMinimum(3);

// Case 1: Fails (only 2 'a's)
wl("--- Case 1: Fails ---")
t.@Text("a b a b");
t.Transform();
wl("Matches Found: ", t.@Matches().Count()) // Should be 0
wl("Result: ", t)

// Case 2: Succeeds (3 'a's)
wl("")
wl("--- Case 2: Succeeds ---")
t.@Text("a b a b a");
t.Transform();
wl("Matches Found: ", t.@Matches().Count()) // Should be 5 (3 'A's and 2 'B's)
wl("Result: ", t)
```

**Output:**
```
--- Case 1: Fails ---
Matches Found: 0
Result: a b a b

--- Case 2: Succeeds ---
Matches Found: 5
Result: A B A B A
```

---

### Example ID: 885

**Description:** Toggling a rule on and off.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var r = t.FromTo("Hello", "Hi");

// Disable
r.@Active(false);
wl(t.Transform("Hello").@Text()) // Output: Hello (No change)

// Enable
r.@Active(true);
wl(t.Transform("Hello").@Text()) // Output: Hi
```

**Output:**
```
Hello
Hi
```

---

### Example ID: 886

**Description:** Simple arithmetic matching.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Match "Number + Number"
t.FromTo("{@Number} + {@Number}", "Math Operation");

wl(t.Transform("10 + 20")) // Output: Math Operation
wl(t.Transform("A + B"))   // No Match (A/B are Alpha, not Number)
```

**Output:**
```
Math Operation
A + B
```

---

### Example ID: 887

**Description:** Parsing Key-Value pairs where values can be numbers or strings.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Use {@Literal} to match either numbers or strings
t.FromTo("{@Alpha:key} = {@Literal:val}", "Set {key} to {val}");

wl(t.Transform("Timeout = 100"))      // Output: Set Timeout to 100
wl(t.Transform("Name = 'Admin'"))     // Output: Set Name to 'Admin'
```

**Output:**
```
Set Timeout to 100
Set Name to 'Admin'
```

---

### Example ID: 888

**Description:** Converting single-quoted strings to double-quoted ones by targeting the delimiters.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@sq}", [verbatim]"[/verbatim]);

wl(t.Transform("print 'Hello'"))
```

**Output:**
```
print "Hello"
```

---

### Example ID: 889

**Description:** Replacing all horizontal whitespace with a visible underscore for debugging.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@Whitespace}", "_");

wl(t.Transform("x = 10 + y"))
```

**Output:**
```
x_=_10_+_y
```

---

### Example ID: 894

**Description:** Demonstrating the difference between the `(0)` and `(1)` index.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Capture the string and show both versions in the replacement
t.FromTo("{@String:txt}", "With: {txt(0)}, Without: {txt(1)}, Default: {txt}");

wl(t.Transform("'uCalc'"))
```

**Output:**
```
With: 'uCalc', Without: uCalc, Default: uCalc
```

---

### Example ID: 895

**Description:** Converting quoted strings into XML-style elements by stripping the original quotes.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Use {s(1)} to get just the text inside the quotes
t.FromTo("msg = {@String:s}", "<message>{s(1)}</message>");

var(string, input) = [verbatim]msg = "Welcome to uCalc!"[/verbatim];
wl(t.Transform(input))
```

**Output:**
```
<message>Welcome to uCalc!</message>
```

---

### Example ID: 896

**Description:** (Real World: Sensitive Data Redaction) Masking the content of all string literals in a log or script, while preserving the non-string code structure.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Replace every string literal with a placeholder
t.FromTo("{@String}", [verbatim]"[REDACTED]"[/verbatim]);

var(string, log) = [verbatim]UserLogin(id: 101, pass: 'secret123', name: "Admin")[/verbatim];
wl(t.Transform(log))
```

**Output:**
```
UserLogin(id: 101, pass: "[REDACTED]", name: "[REDACTED]")
```

---

### Example ID: 898

**Description:** Identifying any statement separator and replacing it with a standardized tag.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@StatementSeparator}", " [END_STMT]");

wl(t.Transform("x = 10; y = 20"))
```

**Output:**
```
x = 10 [END_STMT] y = 20
```

---

### Example ID: 900

**Description:** Internal Test (Configurability) Verifying that `{@StatementSeparator}` respects the engine's definition (e.g., checking if it correctly ignores a comma used as a parameter separator).

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@StatementSeparator}", "STMT");

// Comma is not a StatementSeparator, so it should be ignored.
wl(t.Transform("func(a, b); next();"))
```

**Output:**
```
func(a, b)STMT next()STMT
```

---

### Example ID: 901

**Description:** (Real World: SQL-style Escaping) Doubling up single quotes to escape them for a SQL query.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@sq}", "''");

var(string, input) = "It's a trap";
wl(t.Transform(input))
```

**Output:**
```
It''s a trap
```

---

### Example ID: 902

**Description:** (Mixed Delimiter Check) Verifying that `{@sq}` captures only single quotes (ignoring double quotes).

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@sq}", "$");

// Only the single quote should be replaced
wl(t.Transform([verbatim]"Hello" and 'World'[/verbatim]))
```

**Output:**
```
"Hello" and $World$
```

---

### Example ID: 903

**Description:** Identifying any operator sequence (single or multi-character) and labeling it.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@Reducible:op}", "[OP:{op}]");
wl(t.Transform("a + b <= c"))
```

**Output:**
```
a [OP:+] b [OP:<=] c
```

---

### Example ID: 906

**Description:** Identifying any quote character and replacing it with a visible tag.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@QuoteChar}", "[Q]");

wl(t.Transform([verbatim]"Double" and 'Single'[/verbatim]))
```

**Output:**
```
[Q]Double[Q] and [Q]Single[Q]
```

---

### Example ID: 907

**Description:** (Real World: Quote Normalizer) Converting all string literals to use double quotes, regardless of whether they were originally single or double quoted.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Convert any quote character found to a double quote
t.FromTo("{@QuoteChar}", [verbatim]"[/verbatim]);

var(string, input) = [verbatim]msg = 'Hello'; val = "World";[/verbatim];
wl(t.Transform(input))
```

**Output:**
```
msg = "Hello"; val = "World";
```

---

### Example ID: 908

**Description:** (Non-delimiter characters) Verifying that `{@QuoteChar}` does not match characters that are not defined as string delimiters in the engine.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@QuoteChar}", "MATCH");

// Backticks (`) are usually not delimiters by default
wl(t.Transform("`Backtick`"))
```

**Output:**
```
`Backtick`
```

---

### Example ID: 909

**Description:** Identifying all numbers in an expression and wrapping them in a "Num" tag.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@Number:n}", "Num({n})");

wl(t.Transform("price = 50 + 5.50"))
```

**Output:**
```
price = Num(50) + Num(5.50)
```

---

### Example ID: 910

**Description:** Verifying that `{@Number}` correctly ignores digits that are part of other tokens (like strings or identifiers).

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@Number}", "FOUND");

// The '2' in 'var2' and the '100' in the string should NOT match
wl(t.Transform([verbatim]var2 = "count is 100" + 50[/verbatim]))
```

**Output:**
```
var2 = "count is 100" + FOUND
```

---

### Example ID: 911

**Description:** Replacing all platform-specific newlines with a generic visible tag.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@Newline}", "[BR]");

[c]string input = "Line 1\nLine 2\r\nLine 3";[/c]
[vb]Dim input = $"Line 1{vbLf}Line 2{vbCrLf}Line 3"[/vb]
wl(t.Transform(input))
```

**Output:**
```
Line 1[BR]Line 2[BR]Line 3
```

---

### Example ID: 912

**Description:** Identifying and removing redundant empty lines (consecutive newlines).

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Match two newlines in a row and replace with one
t.FromTo("{@nl} {@nl}", "{@nl}"); // {@nl} same as {@NewLine}

[c]string text = "First\n\nSecond\n\nThird";[/c]
[vb] Dim text = $"First{vbLf}{vbLf}Second{vbLf}{vbLf}Third"[/vb]
wl(t.Transform(text))
```

**Output:**
```
First
Second
Third
```

---

### Example ID: 914

**Description:** Identifying all literal values in an expression and tagging them.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@Literal:val}", "VAL({val})");

wl(t.Transform([verbatim]x = 10 + "abc"[/verbatim]))
```

**Output:**
```
x = VAL(10) + VAL("abc")
```

---

### Example ID: 915

**Description:** (Real World: Value Masking)

**Code:**
```pseudocode
// Creating a "Clean View" of a log or configuration file by replacing all
// actual data values with a placeholder, leaving only the structural identifiers.
New(uCalc::Transformer, t)
// Replace every literal with a generic placeholder
t.FromTo("{@Literal}", "?");

var(string, input) = [verbatim]setting_a = 500; setting_b = "active";[/verbatim];
wl(t.Transform(input))
```

**Output:**
```
setting_a = ?; setting_b = ?;
```

---

### Example ID: 920

**Description:** Replacing double quotes with single quotes.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@dq}", "'");

wl(t.Transform([verbatim]print "Hello"[/verbatim]))
```

**Output:**
```
print 'Hello'
```

---

### Example ID: 921

**Description:** (Real World: Escaping Helper) Finding double quotes to manually insert an escape backslash before them.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@dq}", [verbatim]\"[/verbatim]);

var(string, input) = [verbatim]He said "Hello"[/verbatim];
wl(t.Transform(input))
```

**Output:**
```
He said \"Hello\"
```

---

### Example ID: 923

**Description:** (Default Matching) Identifying any brackets and normalizing them to a standard parentheses.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@Bracket}", "(");
t.FromTo("{@CloseBracket}", ")");

wl(t.Transform("{a, b, c} f(x, y) [1, 2, 3];"))
```

**Output:**
```
(a, b, c) f(x, y) (1, 2, 3);
```

---

### Example ID: 929

**Description:** Normalizing mixed input by replacing any opening bracket style with a standard parenthesis.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@Bracket}", "(");

wl(t.Transform("{ x + [ y ] }"))
```

**Output:**
```
( x + ( y ] }
```

---

### Example ID: 930

**Description:** (Real World: Structure Identification) Labeling the start of complex data structures in a mixed text stream.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@Bracket}", "[START_SCOPE]");

var(string, input) = "func { data [ 1, 2 ] }";
wl(t.Transform(input))
```

**Output:**
```
func [START_SCOPE] data [START_SCOPE] 1, 2 ] }
```

---

### Example ID: 931

**Description:** (Negative Match) Ensuring that `{@Bracket}` does not match common "bracket-like" characters that are not in its definition (like angle brackets).

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@Bracket}", "FOUND");

// Angle brackets are not included in {@Bracket} by default
wl(t.Transform("vector <int>"))
```

**Output:**
```
vector <int>
```

---

### Example ID: 937

**Description:** Basic distinction between a root rule and a child rule.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var rootRule = t.Pattern("root");
var localTransformer = rootRule.@LocalTransformer();
var childRule = localTransformer.Pattern("child");

wl("Is 'rootRule' a child? ", bool(rootRule.@IsChildRule()))
wl("Is 'childRule' a child? ", bool(childRule.@IsChildRule()))
```

**Output:**
```
Is 'rootRule' a child? False
Is 'childRule' a child? True
```

---

### Example ID: 938

**Description:** Internal Test: Verifies that any rule not on the root transformer is considered a child, regardless of nesting depth.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var grandParentRule = t.Pattern("grandparent");

// Create a child
var parentTransformer = grandParentRule.@LocalTransformer();
var parentRule = parentTransformer.Pattern("parent");

// Create a grandchild
var childTransformer = parentRule.@LocalTransformer();
var childRule = childTransformer.Pattern("child");

wl("Grandparent is child: ", bool(grandParentRule.@IsChildRule()))
wl("Parent is child: ", bool(parentRule.@IsChildRule()))
wl("Child (grandchild) is child: ", bool(childRule.@IsChildRule()))
```

**Output:**
```
Grandparent is child: False
Parent is child: True
Child (grandchild) is child: True
```

---

### Example ID: 939

**Description:** A simple example showing how to extract a value from a nested configuration block.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("Config { setting = 123; }");

// 1. Define the parent rule to capture the content inside the braces.
var parentRule = t.Pattern("Config '{' {body} '}'").SetStatementSensitive(false);

// 2. Get the local transformer for the parent rule.
var local_t = parentRule.@LocalTransformer();

// 3. Define a rule that operates ONLY on the text captured by '{body}'.
local_t.FromTo("setting = {val}", "Found Value: {val}");

// 4. Perform the transformation.
// The local rule will run on the text " setting = 123; ".
t.Transform();

wl(t.@Text())
```

**Output:**
```
Config { Found Value: 123; }
```

---

### Example ID: 940

**Description:** A practical example of parsing a specific HTML section and applying transformations only to the elements within it.

**Code:**
```pseudocode
// Note the change in section/div/h2
var t = uc.NewTransformer();

// The parent rule will find the <section> block and make its content available to a local transformer.
// StatementSensitive(false) is needed so the multiline content is captured.
var parentRule = t.Pattern("<section>{body}</section>");
parentRule.@StatementSensitive(false);

// Get the local transformer for the <section> block.
var section_t = parentRule.@LocalTransformer();

// These rules will ONLY run on the content inside the <section> tag.
section_t.FromTo("<h2>{text}</h2>", "<h1>====> {@Eval: UCase(text)} <====</h1>");
section_t.FromTo("<p>{text}</p>", "<p>SELECTED: {text}</p>");

var sourceHtml = 
[verbatim]
<div>
  <h2>Article One</h2>
  <p>This is NOT in the section.</p>
</div>

<section>
  <div>
    <h2>Article Two</h2>
    <p>This one IS inside the section.</p>
  </div>
</section>
[/verbatim];

t.@Text(sourceHtml);
t.Transform();
wl(t.@Text())
```

**Output:**
```
<div>
  <h2>Article One</h2>
  <p>This is NOT in the section.</p>
</div>

<section>
  <div>
    <h1>====> ARTICLE TWO <====</h1>
    <p>SELECTED: This one IS inside the section.</p>
  </div>
</section>
```

---

### Example ID: 941

**Description:** Internal Test: Verifies the filtering of nested matches using RootLevelOnly and InnermostOnly options.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var txt = "<p id='aa'>xyz</p><p id='bb'>Hello</p ><p id='cc'>World</p>";
t.@Text(txt);

// Parent rule matches the <p> tag. Its local transformer then extracts the 'id' attribute.
var parentRule = t.Pattern("<p {etc}>");
parentRule.@LocalTransformer().FromTo("id={@string:id}", "{id}");
t.Filter();

wl("--- All Matches (Parent and Child) ---")
wl(t.GetMatches(MatchesOption::All).@Text())
wl("")

wl("--- RootLevelOnly (Parent Matches) ---")
wl(t.GetMatches(MatchesOption::RootLevelOnly).@Text())
wl("")

wl("--- InnermostOnly (Child Matches) ---")
wl(t.GetMatches(MatchesOption::InnermostOnly).@Text())
```

**Output:**
```
--- All Matches (Parent and Child) ---
<p aa>
aa
<p bb>
bb
<p cc>
cc

--- RootLevelOnly (Parent Matches) ---
<p aa>
<p bb>
<p cc>

--- InnermostOnly (Child Matches) ---
aa
bb
cc
```

---

### Example ID: 945

**Description:** A basic demonstration of how the Maximum threshold invalidates a rule's matches.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var ruleA = t.FromTo("a", "A");

// Case 1: Limit is 2, but 3 'a's are present. The rule is invalidated.
t.Transform("a b a c a");
ruleA.@Maximum(2);
wl("--- Maximum = 2 (Rule Fails) ---")
w("Result: ")
wl(t.Transform("a b a c a"))

// Case 2: Limit is 3. The rule passes and matches are kept.
ruleA.@Maximum(3);
wl("")
wl("--- Maximum = 3 (Rule Succeeds) ---")
w("Result: ")
wl(t.Transform("a b a c a"))
```

**Output:**
```
--- Maximum = 2 (Rule Fails) ---
Result: a b a c a

--- Maximum = 3 (Rule Succeeds) ---
Result: A b A c A
```

---

### Example ID: 946

**Description:** Practical: Validating log file entries. If more than 2 'WARNING' entries exist, they are ignored, but 'ERROR' entries are still processed.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var log = "WARNING: low disk. ERROR: service down. WARNING: high CPU. WARNING: queue full.";

var warningRule = t.FromTo("WARNING: {msg}.", "[WARN] {msg}.");
var errorRule = t.FromTo("ERROR: {msg}.", "[ERR] {msg}.");

// Set a rule-specific limit for warnings.
warningRule.@Maximum(2);

t.Filter(log);
wl(t.@Matches().@Text())
```

**Output:**
```
[ERR] service down.
```

---

### Example ID: 947

**Description:** Internal Test: Compares the behavior of Maximum (rule-level) and GlobalMaximum (transformer-level) invalidation.

**Code:**
```pseudocode
var FruitsXML = 
[verbatim]
<Fruits>
  <Fruit CommonName='Apple' />
  <Fruit CommonName='Banana' />
  <Fruit CommonName='Orange' />
  <Fruit CommonName='Grapes' />
</Fruits>
[/verbatim];

New(uCalc::Transformer, t)
var fruitsTagRule = t.FromTo("<Fruits>", "List of fruits");
var fruitRule = t.FromTo("CommonName={@string:name}", "- {name}");

wl("--- Using Maximum (Rule-Level Invalidation) ---")
// The fruitRule will fail because there are 4 fruits, exceeding the max of 3.
fruitRule.@Maximum(3);
t.Filter(FruitsXML);
wl("Match count: ", t.@Matches().Count()) // The 'fruitsTagRule' still matches and is counted.
wl(t.@Matches().@Text())

wl("")
wl("--- Using GlobalMaximum (Transformer-Level Invalidation) ---")
fruitRule.@Maximum(-1); // Reset local maximum to default (unlimited).
fruitRule.@GlobalMaximum(3); // The entire transformer will fail if more than 3 fruits are found.
t.Filter(FruitsXML);
wl("Match count: ", t.@Matches().Count()) // All matches (including fruitsTagRule) are invalidated.
wl(t.@Matches().@Text())
```

**Output:**
```
--- Using Maximum (Rule-Level Invalidation) ---
Match count: 1
List of fruits

--- Using GlobalMaximum (Transformer-Level Invalidation) ---
Match count: 0

```

---

### Example ID: 948

**Description:** How a rule fails if it doesn't meet the minimum match count.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var ruleA = t.FromTo("a", "A");
ruleA.@Minimum(3);

wl("--- Case 1: Fails (only 2 'a's) ---")
t.Transform("a b a b c");
wl("Result: ", t)
wl("Matches Found: ", t.@Matches().Count())

wl("")
wl("--- Case 2: Succeeds (3 'a's) ---")
t.Transform("a b a b a c");
wl("Result: ", t)
wl("Matches Found: ", t.@Matches().Count())
```

**Output:**
```
--- Case 1: Fails (only 2 'a's) ---
Result: a b a b c
Matches Found: 0

--- Case 2: Succeeds (3 'a's) ---
Result: A b A b A c
Matches Found: 3
```

---

### Example ID: 949

**Description:** A practical example where a 'data' rule is invalidated if it appears too few times, while a 'header' rule is unaffected.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var document = [verbatim]
Header: Section 1
Data: A
Data: B
Header: Section 2
Data: C
[/verbatim];
t.@Text(document);

var dataRule = t.Pattern("Data: {val}");
var headerRule = t.Pattern("Header: {val}");

dataRule.@Minimum(2);
wl("--- Find with Minimum(2) ---")
t.Find();
wl("Total Matches: ", t.@Matches().Count())
wl("Data Matches: ", dataRule.@Matches().Count())
wl("Header Matches: ", headerRule.@Matches().Count())

dataRule.@Minimum(4);
wl("")
wl("--- Find with Minimum(4) ---")
t.Find();
wl("Total Matches: ", t.@Matches().Count())
wl("Data Matches: ", dataRule.@Matches().Count())
wl("Header Matches: ", headerRule.@Matches().Count())
```

**Output:**
```
--- Find with Minimum(2) ---
Total Matches: 5
Data Matches: 3
Header Matches: 2

--- Find with Minimum(4) ---
Total Matches: 2
Data Matches: 0
Header Matches: 2
```

---

### Example ID: 950

**Description:** Internal Test: Clearly contrasts the rule-level invalidation of `Minimum` with the transformer-level invalidation of `GlobalMinimum`.

**Code:**
```pseudocode
var FruitsXML = 
[verbatim]
<Fruits>
  <Fruit CommonName='Apple' />
  <Fruit CommonName='Banana' />
  <Fruit CommonName='Orange' />
</Fruits>
[/verbatim];

New(uCalc::Transformer, t)
t.@Text(FruitsXML);
var fruitsTagRule = t.Pattern("<Fruits>");
var fruitRule = t.Pattern("CommonName={@string:name}");

wl("--- Using Minimum (Rule-Level Invalidation) ---")
fruitRule.@Minimum(4); // Rule fails if fewer than 4 fruits are found.
t.Find();
wl("Match count when fruit rule fails: ", t.@Matches().Count())
wl("Matches found:")
foreach(var m in t.@Matches())
    wl("  ", m.@Text())
end foreach;

wl("")
wl("--- Using GlobalMinimum (Transformer-Level Invalidation) ---")
fruitRule.@Minimum(0); // Reset local minimum
fruitRule.@GlobalMinimum(4); // Transformer fails if fewer than 4 fruits are found.
t.Find();
wl("Match count when global rule fails: ", t.@Matches().Count())
wl("Matches found:")
foreach(var m in t.@Matches())
    wl("  ", m.@Text())
end foreach;
```

**Output:**
```
--- Using Minimum (Rule-Level Invalidation) ---
Match count when fruit rule fails: 1
Matches found:
  <Fruits>

--- Using GlobalMinimum (Transformer-Level Invalidation) ---
Match count when global rule fails: 0
Matches found:
```

---

### Example ID: 951

**Description:** A simple demonstration of how a rule's name is derived from the first token in its pattern.

**Code:**
```pseudocode
New(uCalc::Transformer, t)

var rule1 = t.FromTo("Hello {name}", "Hi {name}");
var rule2 = t.Pattern("<h1>{title}</h1>");

wl("Rule 1 Name: '", rule1.@Name(), "'")
wl("Rule 2 Name: '", rule2.@Name(), "'")
```

**Output:**
```
Rule 1 Name: 'hello'
Rule 2 Name: '<'
```

---

### Example ID: 952

**Description:** A practical example showing how to iterate through all matches and print the name of the rule that generated each one for debugging.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Text("Log: INFO, Data: 123, Log: WARN");

// Define two rules with different starting anchors
t.Pattern("Log: {@Alpha}");
t.Pattern("Data: {@Number}");
t.Find();

wl("--- Match Analysis ---")
foreach (var match in t.@Matches())
    wl("Match '", match.@Text(), "' was found by rule '", match.@Rule().@Name(), "'")
end foreach
```

**Output:**
```
--- Match Analysis ---
Match 'Log: INFO' was found by rule 'log'
Match 'Data: 123' was found by rule 'data'
Match 'Log: WARN' was found by rule 'log'
```

---

### Example ID: 954

**Description:** Demonstrates the basic LIFO (Last-In, First-Out) behavior of NextOverload with two simple rules.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Text("This is a test.");

// Rule 1 (defined first, lower priority)
var rule1 = t.FromTo("is", "[IS_1]");

// Rule 2 (defined second, higher priority)
var rule2 = t.FromTo("is", "[IS_2]");

wl("--- Applying transform (Rule 2 has precedence) ---")
wl(t.Transform())
wl("")

wl("--- Using NextOverload ---")
// Get the rule that comes after rule2
var nextRule = rule2.NextOverload();

wl("Rule 2 pattern: ", rule2.@Pattern())
wl("Next rule's pattern: ", nextRule.@Pattern())

// Verify that the next rule is indeed rule1
wl("Next rule is rule1: ", bool(nextRule.Handle() == rule1.Handle()))
```

**Output:**
```
--- Applying transform (Rule 2 has precedence) ---
This [IS_2] a test.

--- Using NextOverload ---
Rule 2 pattern: is
Next rule's pattern: is
Next rule is rule1: True
```

---

### Example ID: 955

**Description:** Iterates through a chain of rules with the same anchor to inspect their different replacement patterns.

**Code:**
```pseudocode
New(uCalc::Transformer, t)

// Define multiple rules with the same anchor ("Log:")
t.FromTo("Log: {msg}", "DEFAULT: {msg}");
t.FromTo("Log: ERROR {msg}", "CRITICAL: {msg}");
var lastRule = t.FromTo("Log: INFO {msg}", "INFO: {msg}"); // This has the highest priority

wl("--- Overload Chain for 'Log:' anchor ---")
var currentRule = lastRule;
do
   wl("Pattern: '", currentRule.@Pattern(), "' -> Replacement: '", currentRule.@Replacement(), "'")
   currentRule = currentRule.NextOverload();
loop while (currentRule.NotEmpty())
```

**Output:**
```
--- Overload Chain for 'Log:' anchor ---
Pattern: 'Log: INFO {msg}' -> Replacement: 'INFO: {msg}'
Pattern: 'Log: ERROR {msg}' -> Replacement: 'CRITICAL: {msg}'
Pattern: 'Log: {msg}' -> Replacement: 'DEFAULT: {msg}'
```

---

### Example ID: 956

**Description:** Internal Test: Verifies precedence and traversal of rules with different patterns but the same starting anchor ('Testing').

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("Testing (a b c) Testing x y z! Testing 1 2 3.");

var Pattern1 = t.Pattern("Testing {etc}.").SetTag(111);
var Pattern2 = t.Pattern("Testing {etc}!").SetTag(222);
var Pattern3 = t.Pattern("Testing ({etc})").SetTag(333);

t.Find();
wl("--- Matches ---")
wl(t.@Matches().@Text())
wl("--- Patterns ---")
wl(Pattern1.@Pattern())
wl(Pattern2.@Pattern())
wl(Pattern3.@Pattern())
wl("---- Tags ----")
wl(Pattern1.@Tag())
wl(Pattern2.@Tag())
wl(Pattern3.@Tag())
wl("-- Overload Tags --")
// Note that most recently defined patterns come first
wl(Pattern3.NextOverload().@Tag())
wl(Pattern2.NextOverload().@Tag())
wl(Pattern1.NextOverload().@Tag())
```

**Output:**
```
--- Matches ---
Testing (a b c)
Testing x y z!
Testing 1 2 3.
--- Patterns ---
Testing {etc}.
Testing {etc}!
Testing ({etc})
---- Tags ----
111
222
333
-- Overload Tags --
222
111
0
```

---

### Example ID: 960

**Description:** Verifies the direct parent-child relationship between a Transformer and its Rule.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var myRule = t.FromTo("A", "B");

// Get the parent from the rule
var parent = myRule.@ParentTransformer();

// Check if the parent is the original transformer using its unique memory index
wl(bool(parent.@MemoryIndex() == t.@MemoryIndex()))
```

**Output:**
```
True
```

---

### Example ID: 961

**Description:** Iterates through matches, retrieves the rule for each, and uses ParentTransformer to get the transformer's description for context.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Description("My Main Transformer");
t.@Text("apple banana apple");

var appleRule = t.FromTo("apple", "APPLE");
var bananaRule = t.FromTo("banana", "BANANA");

t.Find();

foreach(var match in t.@Matches())
    var rule = match.@Rule();
    var parent = rule.@ParentTransformer();
    wl("Match '", match.@Text(), "' found by rule '", rule.@Name(), "' in transformer '", parent.@Description(), "'")
end foreach
```

**Output:**
```
Match 'apple' found by rule 'apple' in transformer 'My Main Transformer'
Match 'banana' found by rule 'banana' in transformer 'My Main Transformer'
Match 'apple' found by rule 'apple' in transformer 'My Main Transformer'
```

---

### Example ID: 962

**Description:** Internal Test: Verifies that the correct parent is returned when using a nested LocalTransformer, confirming hierarchical integrity.

**Code:**
```pseudocode
New(uCalc::Transformer, main_t)
main_t.@Description("Main Transformer");

// Create an outer rule in the main transformer
var outerRule = main_t.Pattern("OUTER({body})");

// Get a local transformer for the outer rule
var local_t = outerRule.@LocalTransformer();
local_t.@Description("Local Transformer");

// Create an inner rule inside the local transformer
var innerRule = local_t.FromTo("INNER", "inner_match");

// Verify the parent of the outer rule is the main transformer
wl("Outer rule's parent: ", outerRule.@ParentTransformer().@Description())

// Verify the parent of the inner rule is the local transformer
wl("Inner rule's parent: ", innerRule.@ParentTransformer().@Description())
```

**Output:**
```
Outer rule's parent: Main Transformer
Inner rule's parent: Local Transformer
```

---

### Example ID: 963

**Description:** How to retrieve the pattern string from a defined rule.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var rule = t.FromTo("Hello {name}", "Greetings, {name}!");

wl("Rule pattern is: '", rule.@Pattern(), "'")
```

**Output:**
```
Rule pattern is: 'Hello {name}'
```

---

### Example ID: 964

**Description:** A practical debugging example that identifies which pattern string generated each match.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("An apple and a car.");

// Define two separate rules
t.FromTo("apple", "[FRUIT]");
t.FromTo("car", "[VEHICLE]");

t.Find();

var matches = t.@Matches();
wl("Found ", matches.Count(), " matches:")
foreach(var match in matches)
    var rule = match.@Rule();
    wl("- Matched '", match.@Text(), "' using pattern: '", rule.@Pattern(), "'")
end foreach
```

**Output:**
```
Found 2 matches:
- Matched 'apple' using pattern: 'apple'
- Matched 'car' using pattern: 'car'
```

---

### Example ID: 965

**Description:** Internal Test: Verifies that the correct pattern string is returned for rules created with both FromTo() and Pattern(), including complex syntax.

**Code:**
```pseudocode
var t = uc.NewTransformer();

// Rule created with FromTo
var rule1 = t.FromTo("Key: {@Number:val}", "{val}");

// Rule created with Pattern
var rule2 = t.Pattern("<{tag}>{content}</{tag}>");

wl("Rule 1 Pattern: ", rule1.@Pattern())
wl("Rule 2 Pattern: ", rule2.@Pattern())
```

**Output:**
```
Rule 1 Pattern: Key: {@Number:val}
Rule 2 Pattern: <{tag}>{content}</{tag}>
```

---

### Example ID: 970

**Description:** Demonstrates the default `QuoteSensitive(true)` behavior, where a pattern match is ignored inside a string literal.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("fox", "CAT");

// The 'fox' inside the quotes is not replaced.
wl(t.Transform("The quick brown fox jumps over the 'lazy fox'."))
```

**Output:**
```
The quick brown CAT jumps over the 'lazy fox'.
```

---

### Example ID: 971

**Description:** Practical: Creates a custom code block parser. `@QuoteSensitive(false)` is essential to allow the capture of content that contains its own quotes.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var source = [verbatim]Some text... [code]print("Hello, World!") // Quoted with "
var x = 'test';[/code] ...more text.[/verbatim];

// This rule must disable QuoteSensitive and StatementSensitive to correctly
// capture the multi-line block containing single and double quotes.
var rule = t.FromTo("'['code']'{content}'['/code']'", [verbatim]```
{content}
```[/verbatim]);
rule.@QuoteSensitive(false);
rule.@StatementSensitive(false);

wl(t.Transform(source))
```

**Output:**
```
Some text... ```
print("Hello, World!") // Quoted with "
var x = 'test';
``` ...more text.
```

---

### Example ID: 975

**Description:** Internal Test: Verifies that releasing a rule correctly 'un-shadows' a previously defined rule with the same pattern.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Text("The quick brown fox.");

// 1. Define the original rule
var ruleV1 = t.FromTo("brown", "BROWN_V1");
wl("Initial transform: ", t.Transform())

// 2. Define a new rule with the same pattern, shadowing the original
t.@Text("The quick brown fox.");
var ruleV2 = t.FromTo("brown", "BROWN_V2");
wl("After shadowing: ", t.Transform())

// 3. Release the new rule. The original rule should become active again.
t.@Text("The quick brown fox.");
ruleV2.Release();
wl("After release (reverted): ", t.Transform())
```

**Output:**
```
Initial transform: The quick BROWN_V1 fox.
After shadowing: The quick BROWN_V2 fox.
After release (reverted): The quick BROWN_V1 fox.
```

---

### Example ID: 979

**Description:** The cascading effect of enabling `RewindOnChange`.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Rule 1: Replace 'A' with 'B'. Rewind is off by default.
t.FromTo("A", "B");
// Rule 2: Replace 'B' with 'C'.
t.FromTo("B", "C");

wl("--- Rewind Disabled ---")
// The 'A' becomes 'B', but the scan continues *after* the 'B', so rule 2 is not triggered.
wl(t.Transform("Start A End"))
t.Reset();

// Now, enable rewind on the first rule.
t.FromTo("A", "B").@RewindOnChange(true);
t.FromTo("B", "C");

wl("")
wl("--- Rewind Enabled ---")
// The 'A' becomes 'B', rewind occurs, the 'B' is re-scanned and becomes 'C'.
wl(t.Transform("Start A End"))
```

**Output:**
```
--- Rewind Disabled ---
Start B End

--- Rewind Enabled ---
Start C End
```

---

### Example ID: 980

**Description:** Demonstrates using `RewindOnChange` to create a recursive `AddUp` function within the expression transformer.

**Code:**
```pseudocode
var t = uc.@ExpressionTransformer();  // Transformer used for Eval() and Evaluate()

var p1 = t.FromTo("AddUp({x})", "{x}"); // Base case
var p2 = t.FromTo("AddUp({x}, {y})", "({x} + AddUp({y}))").SetRewindOnChange(true); // Recursive step

wl("p1 RewindOnChange: ", bool(p1.@RewindOnChange()))
wl("p2 RewindOnChange: ", bool(p2.@RewindOnChange()))

wl("")
wl("Input: ", "AddUp(1,2,3,4)")
wl("Transform: ", t.Transform("AddUp(1,2,3,4)"))
wl("Eval: ", uc.Eval("AddUp(1,2,3,4)"))
```

**Output:**
```
p1 RewindOnChange: False
p2 RewindOnChange: True

Input: AddUp(1,2,3,4)
Transform: (1 + (2 + (3 + 4)))
Eval: 10
```

---

### Example ID: 981

**Description:** Applies `RewindOnChange` to a default rule set to enable complex, multi-rule transformations for a custom `Average` function.

**Code:**
```pseudocode
var t = uc.@ExpressionTransformer();

// Enable rewind for all subsequent rules in this transformer.
t.@DefaultRuleSet().SetRewindOnChange(true);

// Define the recursive rules.
t.FromTo("AddUp({x})", "{x}");
t.FromTo("AddUp({x}, {y})", "({x} + AddUp({y}))");

t.FromTo("ArgCount({x})", "1");
t.FromTo("ArgCount({x}, {y})", "(1 + ArgCount({y}))");

// The main rule that combines the others.
t.FromTo("Average({x}, {y})", "AddUp({x}, {y}) / ArgCount({x}, {y})");

var expression = "Average(1, 2, 3, 4)";
wl("Input: ", expression)
wl("Transform: ", t.Transform(expression))
wl("Eval: ", uc.Eval(expression))
```

**Output:**
```
Input: Average(1, 2, 3, 4)
Transform: (1 + (2 + (3 + 4))) / (1 + (1 + (1 + 1)))
Eval: 2.5
```

---

### Example ID: 985

**Description:** Finding all occurrences of a letter except for the first one.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Text("a b c a d e a f g");
var ruleA = t.FromTo("a", "[MATCH]");

// Skip the first 'a' that is found
ruleA.@StartAfter(1);

wl(t.Transform())
```

**Output:**
```
a b c [MATCH] d e [MATCH] f g
```

---

### Example ID: 986

**Description:** A practical example that processes a list of tasks but skips the first two high-priority items.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var taskList = "Task:1 Task:2 Task:3 Task:4 Task:5";
t.@Text(taskList);

var taskRule = t.FromTo("Task:{@Number:id}", "Processed Task {id}");

// Skip the first two tasks in the list
taskRule.@StartAfter(2);

wl(t.Transform())
```

**Output:**
```
Task:1 Task:2 Processed Task 3 Processed Task 4 Processed Task 5
```

---

### Example ID: 988

**Description:** Demonstrates the difference in variable capture behavior when StatementSensitive is enabled versus disabled.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var(string, txt) = "start one; two end";

// Default behavior is StatementSensitive(true), so {body} stops at the semicolon
// and the 'end' anchor is never found. The transform fails.
var rule = t.FromTo("start {body} end", "[{body}]");
wl("Sensitive (default): ", t.Transform(txt))

rule.@StatementSensitive(false);
// With StatementSensitive(false), {body} captures across the semicolon.
wl("Insensitive: ", t.Transform(txt))
```

**Output:**
```
Sensitive (default): start one; two end
Insensitive: [one; two]
```

---

### Example ID: 989

**Description:** Practical: Shows how disabling statement sensitivity is essential for parsing multi-line HTML/XML blocks.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var source = [verbatim]<data>
  content spans
  multiple lines
</data>[/verbatim];

// This rule must disable StatementSensitive to capture the multi-line body,
// otherwise the first newline would terminate the {body} variable.
var rule = t.FromTo("<data>{body}</data>", "Body: [{body}]");
rule.@StatementSensitive(false);

wl(t.Transform(source))
```

**Output:**
```
Body: [
  content spans
  multiple lines
]
```

---

### Example ID: 991

**Description:** Finds and transforms only the first three occurrences of a pattern, ignoring any subsequent ones.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("a b c a d e a f g a h i");
var ruleA = t.FromTo("a", "[A]");

// Only find and transform the first 3 occurrences of 'a'.
ruleA.@StopAfter(3);

wl(t.Transform())
```

**Output:**
```
[A] b c [A] d e [A] f g a h i
```

---

### Example ID: 992

**Description:** Processes a log file but stops after finding the first error message to focus on the initial problem.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var logText = "ERROR: Fail 1. INFO: OK. ERROR: Fail 2. ERROR: Fail 3.";
t.@Text(logText);

var errorRule = t.Pattern("ERROR: {msg}.");
// Stop after finding the first error to focus on the initial problem.
errorRule.@StopAfter(1);
t.Find();

wl("First error found: ", t.@Matches().@Text())
```

**Output:**
```
First error found: ERROR: Fail 1.
```

---

### Example ID: 993

**Description:** Internal Test: Combines `@StartAfter` and `@StopAfter` to retrieve a specific 'page' of results (matches 3 through 7).

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("1 2 3 4 5 6 7 8 9 10 11 12");
var rule = t.Pattern("{@Number}");

// Get a "page" of results: matches 3 through 7.
// The engine will stop finding numbers after the 7th match is found.
// Then, it will skip the first 2 matches from that set.
rule.@StartAfter(2); // Skip first 2
rule.@StopAfter(7);  // Find up to 7

t.Find();

wl("Matches found:")
wl(t.@Matches().@Text())
```

**Output:**
```
Matches found:
3
4
5
6
7
```

---

### Example ID: 994

**Description:** How to set and get tags for different rules.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var ruleA = t.Pattern("A").SetTag(10);
var ruleB = t.Pattern("B").SetTag(20);

wl("Tag for Rule A: ", ruleA.@Tag())
wl("Tag for Rule B: ", ruleB.@Tag())
```

**Output:**
```
Tag for Rule A: 10
Tag for Rule B: 20
```

---

### Example ID: 995

**Description:** A practical example using tags to build a simple syntax highlighter that categorizes matches.

**Code:**
```pseudocode
// Practical: Basic Syntax Highlighter
New(uCalc::Transformer, t)

// Define categories with integer tags
var TAG_KEYWORD = 1;
var TAG_STRING = 2;
var TAG_COMMENT = 3;

// Define rules and tag them
t.Pattern("{ if | else | for | while }").SetTag(TAG_KEYWORD);
t.Pattern("{@String}").SetTag(TAG_STRING);
t.Pattern("// {text}").SetTag(TAG_COMMENT);

t.@Text([verbatim]for (i=0; i<10; i++) { s = "hello"; // comment }[/verbatim]);
t.Find();

foreach (var match in t.@Matches())
    var tag = match.@Rule().@Tag();
    if (tag == TAG_KEYWORD)
        wl("TAG_KEYWORD: ", match.@Text())
    else if (tag == TAG_STRING)
        wl("TAG_STRING: ", match.@Text())
    else if (tag == TAG_COMMENT)
        wl("TAG_COMMENT: ", match.@Text())
    end if
end foreach
```

**Output:**
```
TAG_KEYWORD: for
TAG_STRING: "hello"
TAG_COMMENT: // comment 
```

---

### Example ID: 996

**Description:** Internal Test: Verifies rule precedence and tag retrieval by traversing the overload chain with NextOverload.

**Code:**
```pseudocode
// Internal Test: Verifies precedence and tag retrieval via NextOverload
New(uCalc::Transformer, t)
t.@Text("Testing (a b c) Testing x y z! Testing 1 2 3.");

// Rules defined last have higher precedence for the same anchor ("Testing")
var p1 = t.Pattern("Testing {etc}.").SetTag(111);
var p2 = t.Pattern("Testing {etc}!").SetTag(222);
var p3 = t.Pattern("Testing ({etc})").SetTag(333);

// Get the highest precedence rule via Pattern's return value
var highestPriorityRule = p3;
wl("Highest priority rule tag: ", highestPriorityRule.@Tag())

// Walk the overload chain
var midPriorityRule = highestPriorityRule.NextOverload();
wl("Mid priority rule tag: ", midPriorityRule.@Tag())

var lowPriorityRule = midPriorityRule.NextOverload();
wl("Low priority rule tag: ", lowPriorityRule.@Tag())

// The end of the chain should have a tag of 0 (default)
var endOfChain = lowPriorityRule.NextOverload();
wl("End of chain tag: ", endOfChain.@Tag())
```

**Output:**
```
Highest priority rule tag: 333
Mid priority rule tag: 222
Low priority rule tag: 111
End of chain tag: 0
```

---

### Example ID: 997

**Description:** How to retrieve a rule's parent uCalc instance and verify its identity.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var myRule = t.FromTo("A", "B");

// Get the parent uCalc from the rule
var parent_uc = myRule.@uCalc();

// Verify they are the same instance using their MemoryIndex
wl(bool(parent_uc.@MemoryIndex() == uc.@MemoryIndex()))
```

**Output:**
```
True
```

---

### Example ID: 998

**Description:** A practical example that uses a rule's parent context to define and evaluate an expression.

**Code:**
```pseudocode
// The transformer 't' belongs to the main 'uc' instance.
New(uCalc::Transformer, t(uc))

// Define a variable in the transformer's parent context.
t.@uCalc().DefineVariable("VarX = 123");

// This rule is created within 't' and will need to access VarX.
var myRule = t.FromTo("x", "{@Eval: VarX}");

// Get the rule's parent uCalc instance...
var parent_uc = myRule.@uCalc();

// ...and use it to evaluate an expression to prove we have the right context.
wl("Value of VarX in parent context: ", parent_uc.Eval("VarX"))

// Now, run the transformation. The {@Eval} in the rule
// correctly finds 'VarX' in its parent uCalc context.
wl(t.Transform("The value is: x"))
```

**Output:**
```
Value of VarX in parent context: 123
The value is: 123
```

---

### Example ID: 999

**Description:** Internal Test: Verifies that a rule defined in a nested LocalTransformer correctly resolves its parent to the root uCalc instance.

**Code:**
```pseudocode
New(uCalc, root_uc)
root_uc.@Description("Root uCalc Instance");

New(uCalc::Transformer, main_t(root_uc))

// Create a rule in the main transformer
var outerRule = main_t.Pattern("OUTER({body})");

// Get a local transformer for the outer rule
var local_t = outerRule.@LocalTransformer();
local_t.@Description("Local Transformer");

// Create an inner rule inside the local transformer
var innerRule = local_t.FromTo("INNER", "inner_match");

// Verify both rules resolve to the same root uCalc instance
var outerParent = outerRule.@uCalc();
var innerParent = innerRule.@uCalc();

wl("Outer rule's parent: ", outerParent.@Description())
wl("Inner rule's parent: ", innerParent.@Description())
wl("Both rules share the same root uCalc instance: ", bool(outerParent.Handle() == innerParent.Handle()))
```

**Output:**
```
Outer rule's parent: Root uCalc Instance
Inner rule's parent: Root uCalc Instance
Both rules share the same root uCalc instance: True
```

---

### Example ID: 1003

**Description:** A simple demonstration of defining a token in one transformer and reusing it in another.

**Code:**
```pseudocode
New(uCalc::Transformer, t1)
New(uCalc::Transformer, t2)

// Define a custom token in the first transformer
var customToken = t1.@Tokens().Add("###", TokenType::Generic);

// Import the token definition into the second transformer
t2.@Tokens().Add(customToken);
t2.FromTo("###", "MATCH");

wl("t2 can now find '###': ", t2.Transform("Test ### Test"))
```

**Output:**
```
t2 can now find '###': Test MATCH Test
```

---

### Example ID: 1004

**Description:** Shows how importing a comment token definition can prevent find-and-replace rules from incorrectly modifying text inside comments.

**Code:**
```pseudocode
// Create a transformer with a custom comment token definition
New(uCalc::Transformer, t_source)
var commentToken = t_source.@Tokens().Add([verbatim]/\*([\s\S]*?)\*/[/verbatim], TokenType::Whitespace);
commentToken.@Description("C-style block comment");

// Create a second transformer that will do replacements
New(uCalc::Transformer, t_replacer)
t_replacer.FromTo("secret", "REDACTED");

var sourceText = "a secret /* contains another secret */ value";

wl("--- Before Importing Comment Token ---")
// Without knowing about comments, t_replacer incorrectly modifies the text inside the comment.
wl(t_replacer.Transform(sourceText))
wl("")

wl("--- After Importing Comment Token ---")
// Import the comment token definition. Now, the comment block is treated as a single whitespace token.
t_replacer.@Tokens().Add(commentToken);
// The transformer must be reset with the original text for the new token to apply.
t_replacer.@Text(sourceText); 
wl(t_replacer.Transform())
```

**Output:**
```
--- Before Importing Comment Token ---
a REDACTED /* contains another REDACTED */ value

--- After Importing Comment Token ---
a REDACTED /* contains another secret */ value
```

---

### Example ID: 1006

**Description:** Defines a C-style line comment token (`//...`) and categorizes it as whitespace so it is ignored by the parser.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// By default, a comment would cause a syntax error.
w("Before: ")
wl(uc.EvalStr("10 + 5 // Add 5"))

// Add a new token definition for C-style comments.
// The regex `//.*` matches from '//' to the end of the line.
// We classify it as Whitespace so the parser skips it.
uc.@ExpressionTokens().Add("//.*", TokenType::Whitespace);

w("After:  ")
wl(uc.EvalStr("10 + 5 // Add 5"))
```

**Output:**
```
Before: Undefined identifier
After:  15
```

---

### Example ID: 1008

**Description:** Internal Test: Verifies that the `subMatchGroup` parameter correctly extracts a capture group's content and that `ItemIs::QuotedText` works as expected.

**Code:**
```pseudocode
var t = uc.NewTransformer();

// Define a custom string literal using pipe characters `|...|`.
// The regex `\|([^\|]*)\|` captures the inner content in group 1.
// We set `subMatchGroup` to 1 to use this group as the token's value.
var pipeStringToken = t.@Tokens().Add([verbatim]\|([^\|]*)\|[/verbatim], TokenType::Literal, "", 1);

// Complete the definition by setting the data type and QuotedText property.
pipeStringToken.@DataType(uc.DataTypeOf("String"));
pipeStringToken.IsProperty(ItemIs::QuotedText, true);

// Define a simple rule to prove the token works.
t.FromTo("Test: {@String:s}", "Found: {s(0)} | Content: {s(1)}");

// The transformer now recognizes |...| as a string literal.
wl(t.Transform("Test: |hello|"))
```

**Output:**
```
Found: |hello| | Content: hello
```

---

### Example ID: 1009

**Description:** How to define a custom token in one transformer and reuse it in another.

**Code:**
```pseudocode
// Create a source transformer and define a custom token.
New(uCalc::Transformer, t_source)
var customToken = t_source.@Tokens().Add("###", TokenType::Generic);

// Create a destination transformer.
New(uCalc::Transformer, t_dest)

// Import all token definitions from the source.
t_dest.@Tokens().Add(t_source.@Tokens());
t_dest.FromTo("###", "MATCH");

wl("t_dest can now find '###': ", t_dest.Transform("Test ### Test"))
```

**Output:**
```
t_dest can now find '###': Test MATCH Test
```

---

### Example ID: 1012

**Description:** Retrieves a built-in token by its name and inspects its regex pattern.

**Code:**
```pseudocode
var tokens = uc.@ExpressionTokens();
var alphaToken = tokens.ByName("_token_alphanumeric");
wl("Alphanumeric Regex: ", alphaToken.@Regex())
```

**Output:**
```
Alphanumeric Regex: [a-zA-Z_][a-zA-Z0-9_]*
```

---

### Example ID: 1013

**Description:** Dynamically re-categorizes the newline token to treat it as whitespace, allowing a pattern to match across multiple lines.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var source = [verbatim]<data>
  content spans
  multiple lines
</data>[/verbatim];
t.FromTo("<data>{body}</data>", "Body: [{body}]");

wl("--- Before: Newline is a Separator ---")
wl(t.Transform(source))

// Use ByName to find the newline token and change its type.
t.@Tokens().ByName("_token_newline", TokenType::Whitespace);

wl("")
wl("--- After: Newline is Whitespace ---")
wl(t.Transform(source))
```

**Output:**
```
--- Before: Newline is a Separator ---
<data>
  content spans
  multiple lines
</data>

--- After: Newline is Whitespace ---
Body: [content spans
  multiple lines]
```

---

### Example ID: 1018

**Description:** Retrieves the primary alphanumeric token definition using `ByType`.

**Code:**
```pseudocode
var tokens = uc.@ExpressionTokens();
var alphaToken = tokens.ByType(TokenType::AlphaNumeric);

wl("Name: ", alphaToken.@Name())
wl("Regex: ", alphaToken.@Regex())
```

**Output:**
```
Name: _token_alphanumeric
Regex: [a-zA-Z_][a-zA-Z0-9_]*
```

---

### Example ID: 1019

**Description:** Practical: Iterates through all tokens categorized as 'Literal' to display their definitions.

**Code:**
```pseudocode
var tokens = uc.@ExpressionTokens();
var(int, i) = 0;
New(uCalc::Item, literalToken)

wl("--- All Literal Tokens ---")
do
   literalToken = tokens.ByType(TokenType::Literal, i);
   if (literalToken.NotEmpty())
      wl(i, ": ", literalToken.@Name(), " - ", literalToken.@Regex())
   end if
   i = i + 1;
loop while(literalToken.NotEmpty())
```

**Output:**
```
--- All Literal Tokens ---
0: _token_string_singlequoted - '([^']*(?:''[^']*)*)'
1: _token_string_doublequoted - "([^"]*(?:""[^"]*)*)"
2: _token_string_tripledoublequoted - """([\s\S]*?)"""
3: _token_floatnumber - [0-9]*\.?[0-9]+([eE][+-]?[0-9]+)?
4: _token_imaginaryunit - #i
```

---

### Example ID: 1020

**Description:** Internal Test: Verifies that requesting an out-of-bounds index for a token type returns an empty item.

**Code:**
```pseudocode
var tokens = uc.@ExpressionTokens();

// There is only one Alphanumeric token, so index 1 is out of bounds.
var outOfBoundsToken = tokens.ByType(TokenType::AlphaNumeric, 1);

wl("Is token empty? ", bool(outOfBoundsToken.IsEmpty()))
wl("Was token found? ", bool([cs]![/cs][NotCs]not[/NotCs] outOfBoundsToken.IsProperty(ItemIs::NotFound)))
```

**Output:**
```
Is token empty? True
Was token found? False
```

---

### Example ID: 1021

**Description:** Demonstrates the basic functionality of clearing default tokens and adding a single new one.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("is", "<IS>");

wl("--- With Default Tokens ---")
// By default, 'is' is a whole word (token)
wl(t.Transform("This is a test"))

// Clear all default token definitions
t.@Tokens().Clear();

// Add a new, simple token that matches any single character
t.@Tokens().Add(".");

wl("")
wl("--- After Clearing and Adding '.' Token ---")
// Now, 'i' and 's' are matched as separate characters
t.FromTo("is", "<IS>"); // The rule must be redefined
wl(t.Transform("This is a test"))
```

**Output:**
```
--- With Default Tokens ---
This <IS> a test

--- After Clearing and Adding '.' Token ---
Th<IS> <IS> a test
```

---

### Example ID: 1027

**Description:** Using a context switch to prevent transformations inside a designated `[RAW]` block.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var(string, text) = "Replace config, but not the one inside [RAW]this config is raw[/RAW].";

// Create a token set for the raw block that only tokenizes single characters.
New(uCalc::Transformer, rawTransformer)
var rawTokens = rawTransformer.@Tokens();
rawTokens.Clear();
rawTokens.Add("."); // Match any single character

// Switch to rawTokens when [RAW] is found, and switch back at [/RAW].
t.@Tokens().ContextSwitch(rawTokens, [verbatim]\[RAW\][/verbatim], [verbatim]\[/RAW\][/verbatim]);

t.FromTo("config", "SETTING");

wl(t.Transform(text))
```

**Output:**
```
Replace SETTING, but not the one inside [RAW]this config is raw[/RAW].
```

---

### Example ID: 1030

**Description:** How to get the count of default token definitions.

**Code:**
```pseudocode
var tokenCount = uc.@ExpressionTokens().@Count();
wl("Default expression parser has ", tokenCount, " token definitions.")
```

**Output:**
```
Default expression parser has 30 token definitions.
```

---

### Example ID: 1031

**Description:** A practical example of iterating through all token definitions in a collection using Count as the loop boundary.

**Code:**
```pseudocode
New(uCalc::Transformer, t)

var tokens = t.@Tokens();
wl("Total token definitions: ", tokens.@Count())
wl("--- Token List ---")

var i = 0;

for(i = 0 to tokens.@Count() - 1)
    var tokenItem = tokens.At(i);
    wl(i, ": ", tokenItem.@Name())
end for
```

**Output:**
```
Total token definitions: 27
--- Token List ---
0: _token_line
1: _token_catchall
2: _token_catchall_utf8_other
3: _token_punctuation
4: _token_quotechar
5: _token_quotechar_single
6: _token_quotechar_double
7: _token_quotechar_tripledouble
8: _token_memberaccess
9: _token_variableargs
10: _token_reducible2
11: _token_parenthesis
12: _token_parenthesis_close
13: _token_curlybrace
14: _token_curlybrace_close
15: _token_squarebracket
16: _token_squarebracket_close
17: _token_argseparator
18: _token_newline
19: _token_semicolon
20: _token_string_singlequoted
21: _token_string_doublequoted
22: _token_string_tripledoublequoted
23: _token_whitespace
24: _token_reducible
25: _token_floatnumber
26: _token_alphanumeric
```

---

### Example ID: 1032

**Description:** Internal Test: Verifies that the count updates correctly after Add() and Clear() operations, demonstrating the dynamic nature of the collection.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var tokens = t.@Tokens();

var initialCount = tokens.@Count();
wl("1. Initial count: ", initialCount)

// Add a new token
tokens.Add("custom_token");
wl("2. Count after Add: ", tokens.@Count())

// Clear all tokens
tokens.Clear();
wl("3. Count after Clear: ", tokens.@Count())

// Add one token back
tokens.Add(".");
wl("4. Count after adding one back: ", tokens.@Count())
```

**Output:**
```
1. Initial count: 27
2. Count after Add: 28
3. Count after Clear: 0
4. Count after adding one back: 1
```

---

### Example ID: 1033

**Description:** Demonstrates the basic getter and setter functionality of the Description property.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var tokens = t.@Tokens();

// Set a description
tokens.@Description("Default token set for general purpose parsing.");

// Get the description
wl(tokens.@Description())
```

**Output:**
```
Default token set for general purpose parsing.
```

---

### Example ID: 1034

**Description:** Uses descriptions to identify and differentiate between two separate token configurations at runtime.

**Code:**
```pseudocode
// Create two transformers with different token configurations
New(uCalc::Transformer, strict_t)
strict_t.@Tokens().@Description("Strict Mode: only 'is' as a whole word.");

New(uCalc::Transformer, flexible_t)
flexible_t.@Tokens().@Description("Flexible Mode: matches 'is' inside other words.");
flexible_t.@Tokens().Clear();
flexible_t.@Tokens().Add("."); // Match by character

var(string, text) = "This island is nice.";

strict_t.FromTo("is", "[MATCH]");
flexible_t.FromTo("is", "[MATCH]");

wl(strict_t.@Tokens().@Description())
wl("Result: ", strict_t.Transform(text))
wl("")
wl(flexible_t.@Tokens().@Description())
wl("Result: ", flexible_t.Transform(text))
```

**Output:**
```
Strict Mode: only 'is' as a whole word.
Result: This island [MATCH] nice.

Flexible Mode: matches 'is' inside other words.
Result: Th[MATCH] [MATCH]land [MATCH] nice.
```

---

### Example ID: 1035

**Description:** Internal Test: Verifies that descriptions are copied when token sets are imported, but remain independent afterward.

**Code:**
```pseudocode
New(uCalc::Transformer, t1)
t1.@Tokens().@Description("Original Description");

// Create a new transformer and import tokens from t1
New(uCalc::Transformer, t2)
t2.@Tokens().Add(t1.@Tokens());

wl("t2's initial description (copied from t1): ", t2.@Tokens().@Description())

// Modify t2's description
t2.@Tokens().@Description("Modified Description");

wl("t2's new description: ", t2.@Tokens().@Description())
wl("t1's description remains unchanged: ", t1.@Tokens().@Description())
```

**Output:**
```
t2's initial description (copied from t1): Original Description
t2's new description: Modified Description
t1's description remains unchanged: Original Description
```

---

### Example ID: 1036

**Description:** How adding tokens affects their index and, therefore, their precedence.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var tokens = t.@Tokens();
tokens.Clear();
tokens.Add("."); // Add a fallback token at index 0

// The order of definition determines the index (precedence)
var tokenA = tokens.Add("A");
var tokenB = tokens.Add("B");

wl("Index of A: ", tokens.IndexOf(tokenA)) // Will have a lower index
wl("Index of B: ", tokens.IndexOf(tokenB)) // Will have a higher index, thus higher precedence
```

**Output:**
```
Index of A: 1
Index of B: 2
```

---

### Example ID: 1037

**Description:** Internal Test: Verifies the LIFO precedence order and the return value for a token not present in the collection.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var tokens = t.@Tokens();
tokens.Clear();
tokens.Add("."); // Fallback

var tokenPlus = tokens.Add("[+]");
var tokenStar = tokens.Add("[*]");
var tokenCaret = tokens.Add("^");

// LIFO order means precedence is: '^' > '*' > '+'
wl("Precedence Check:")
wl("Caret (^) > Star (*): ", bool(tokens.IndexOf(tokenCaret) > tokens.IndexOf(tokenStar)))
wl("Star (*) > Plus (+): ", bool(tokens.IndexOf(tokenStar) > tokens.IndexOf(tokenPlus)))

// Test for a token not in this collection
New(uCalc::Transformer, t2)
var unaddedToken = t2.@Tokens().Add("unrelated");
wl("Index of un-added token: ", tokens.IndexOf(unaddedToken))
```

**Output:**
```
Precedence Check:
Caret (^) > Star (*): True
Star (*) > Plus (+): True
Index of un-added token: -1
```

---

### Example ID: 1046

**Description:** Practical: Demonstrates how removing the token for single-quoted strings causes the parser to treat the quote and its contents as individual generic tokens.

**Code:**
```pseudocode
// This example removes the single-quoted string token.
New(uCalc::Transformer, t)
var(string, txt) = "This is a test, 'This is a test'";
t.FromTo("{token:1}", "<{@Self}>");

wl("--- Before Removing Token ---")
// Initially, 'This is a test' is treated as a single token.
wl(t.Transform(txt).@Text())

// Now, find and remove the token definition for single-quoted strings.
var singleQuoteToken = t.@Tokens().ByName("_token_string_singlequoted");
t.@Tokens().Remove(singleQuoteToken);

// Re-run the transform. The text must be set again to be re-tokenized.
t.@Text(txt);
wl("")
wl("--- After Removing Token ---")
// Now, the single quote is a generic token, as are the words inside it.
wl(t.Transform().@Text())
```

**Output:**
```
--- Before Removing Token ---
<This> <is> <a> <test><,> <'This is a test'>

--- After Removing Token ---
<This> <is> <a> <test><,> <'><This> <is> <a> <test><'>
```

---

### Example ID: 1047

**Description:** Internal Test: Removes the core alphanumeric token to verify that the tokenizer falls back to character-by-character tokenization.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var(string, text) = "word game";
t.FromTo("{token:1}", "[{@Self}]");

wl("--- Before Remove ---")
// By default, 'word' is a single alphanumeric token.
wl(t.Transform(text))

// Remove the alphanumeric token definition.
var alphaToken = t.@Tokens().ByName("_token_alphanumeric");
t.@Tokens().Remove(alphaToken);

// The transformer must be reset with the original text for the change to apply.
t.@Text(text);

wl("")
wl("--- After Remove ---")
// Now, 'word' is no longer a single token. The fallback '.' token
// matches each character individually.
wl(t.Transform())
```

**Output:**
```
--- Before Remove ---
[word] [game]

--- After Remove ---
[w][o][r][d] [g][a][m][e]
```

---

### Example ID: 1048

**Description:** Retrieves a Tokens collection's parent uCalc instance and verifies its identity by reading a description.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@uCalc().@Description("My Parent uCalc");
var tokens = t.@Tokens();

// Get the parent from the Tokens object
var parent_uc = tokens.@uCalc();

// Verify we got the correct parent
wl(parent_uc.@Description())
```

**Output:**
```
My Parent uCalc
```

---

### Example ID: 1049

**Description:** Uses the parent uCalc context from a Tokens object to define a variable that is then used by a transformer rule.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var tokens = t.@Tokens();

// Use the parent uCalc instance to define a variable
tokens.@uCalc().DefineVariable("replacement = 'REPLACED'");

t.FromTo("original", "{@Eval: replacement}");

wl(t.Transform("Test of original value."))
```

**Output:**
```
Test of REPLACED value.
```

---

### Example ID: 1050

**Description:** Internal Test: Verifies instance isolation by ensuring Tokens collections from different uCalc instances correctly resolve to their respective parents.

**Code:**
```pseudocode
New(uCalc, uc1)
New(uCalc, uc2)

New(uCalc::Transformer, t1(uc1))
New(uCalc::Transformer, t2(uc2))

var tokens1 = t1.@Tokens();
var tokens2 = t2.@Tokens();

var parent1 = tokens1.@uCalc();
var parent2 = tokens2.@uCalc();

wl("tokens1 belongs to uc1: ", bool(parent1.Handle() == uc1.Handle()))
wl("tokens2 belongs to uc2: ", bool(parent2.Handle() == uc2.Handle()))
wl("tokens1 does not belong to uc2: ", bool(parent1.Handle() != uc2.Handle()))
```

**Output:**
```
tokens1 belongs to uc1: True
tokens2 belongs to uc2: True
tokens1 does not belong to uc2: True
```

---

### Example ID: 1054

**Description:** Demonstrating that a clone is independent and that modifying it does not affect the original.

**Code:**
```pseudocode
// 1. Create and configure the original transformer
New(uCalc::Transformer, t1)
t1.FromTo("A", "B");
wl("Original Transform: ", t1.Transform("A C A"))

// 2. Clone it
var t2 = t1.Clone();

// 3. Modify the clone. This does not affect the original.
t2.FromTo("C", "D");
wl("Cloned Transform:   ", t2.Transform("A C A"))

// 4. Verify original is unchanged by re-running its transform
wl("Original is Unchanged: ", t1.Transform("A C A"))
t2.Release();
t1.Release();
```

**Output:**
```
Original Transform: B C B
Cloned Transform:   B D B
Original is Unchanged: B C B
```

---

### Example ID: 1055

**Description:** A practical example using Clone() to create a specialized parser from a base template, demonstrating rule inheritance.

**Code:**
```pseudocode
// 1. Create a "base" HTML transformer template
New(uCalc::Transformer, baseHtmlParser)
baseHtmlParser.@Description("Base HTML Parser");
// Rule to skip over comments
baseHtmlParser.SkipOver("<!--{body}->");
// Rule to find any tag
baseHtmlParser.Pattern("<{tag}>");
baseHtmlParser.@DefaultRuleSet().SetStatementSensitive(false);

// 2. Create a specialized clone to find only image tags
var imageParser = baseHtmlParser.Clone();
imageParser.@Description("Image Tag Finder");
imageParser.FromTo("<img {attribs} />", "FOUND_IMG_TAG");

var(string, html) = " <body> <img src='a.jpg' /> <!-- <img src='b.jpg' /> --> </body> ";

// The clone inherits the SkipOver rule from the base, so the commented img tag is ignored.
wl(imageParser.Transform(html))

imageParser.Release();
baseHtmlParser.Release();
```

**Output:**
```
 <body> FOUND_IMG_TAG <!-- <img src='b.jpg' /> --> </body> 
```

---

### Example ID: 1062

**Description:** A basic example demonstrating how to set and get a description for a Transformer.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Description("My First Transformer");
wl("Transformer Description: ", t.@Description())
```

**Output:**
```
Transformer Description: My First Transformer
```

---

### Example ID: 1063

**Description:** Uses descriptions to differentiate between two transformers used for different environments, such as a verbose 'debug' transformer and a silent 'production' one.

**Code:**
```pseudocode
var text = "The value is x";

// 1. Setup Debug Transformer
New(uCalc::Transformer, t_debug)
t_debug.@Description("Debug Transformer (Verbose)");
t_debug.FromTo("x", "100 // debug value");

// 2. Setup Production Transformer
New(uCalc::Transformer, t_prod)
t_prod.@Description("Production Transformer (Clean)");
t_prod.FromTo("x", "100");

wl(t_debug.@Description(), ": ", t_debug.Transform(text))
wl(t_prod.@Description(), ": ", t_prod.Transform(text))
```

**Output:**
```
Debug Transformer (Verbose): The value is 100 // debug value
Production Transformer (Clean): The value is 100
```

---

### Example ID: 1064

**Description:** Internal Test: Verifies that the description property is correctly copied when a Transformer is cloned.

**Code:**
```pseudocode
New(uCalc::Transformer, t_original)
t_original.@Description("Original Transformer");

// Clone the transformer
var t_cloned = t_original.Clone();

wl("Original Description: ", t_original.@Description())
wl("Cloned Description:   ", t_cloned.@Description())

// Modify the clone's description to ensure they are independent
t_cloned.@Description("Cloned and Modified");

wl("Original after mod: ", t_original.@Description())
wl("Cloned after mod:   ", t_cloned.@Description())
```

**Output:**
```
Original Description: Original Transformer
Cloned Description:   Original Transformer
Original after mod: Original Transformer
Cloned after mod:   Cloned and Modified
```

---

### Example ID: 1065

**Description:** Finding all occurrences of a specific word.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Text("apple banana apple cherry apple");
t.Pattern("apple");
t.Find();
wl("Found ", t.@Matches().Count(), " occurrences of 'apple'.")
```

**Output:**
```
Found 3 occurrences of 'apple'.
```

---

### Example ID: 1066

**Description:** A practical example using multiple concurrent patterns to find and categorize log entries.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var logText = "INFO: System start. WARN: Low disk. ERROR: DB connection failed.";
t.@Text(logText);

// Define rules for different log levels
var errorRule = t.Pattern("ERROR: {msg}.");
var warnRule = t.Pattern("WARN: {msg}.");

t.Find();

wl("Total issues found: ", t.@Matches().Count())
wl("--- Error Matches ---")
wl(errorRule.@Matches().@Text())
wl("--- Warning Matches ---")
wl(warnRule.@Matches().@Text())
```

**Output:**
```
Total issues found: 2
--- Error Matches ---
ERROR: DB connection failed.
--- Warning Matches ---
WARN: Low disk.
```

---

### Example ID: 1067

**Description:** Internal Test: Verifies correct precedence with overlapping patterns and confirms that re-running Find produces the same results.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Text("The apple is an apple.");

// Overlapping patterns. The longer one is defined last, so it gets precedence.
t.Pattern("apple");
t.Pattern("an apple");

wl("--- First Find ---")
t.Find();
// The first 'apple' matches the first rule.
// The 'an apple' matches the second (higher precedence) rule.
wl(t.@Matches().@Text())

// Re-running find should produce the exact same result
wl("--- Second Find (no change) ---")
t.Find();
wl(t.@Matches().@Text())
```

**Output:**
```
--- First Find ---
apple
an apple
--- Second Find (no change) ---
apple
an apple
```

---

### Example ID: 1071

**Description:** A simple find-and-replace transformation.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("Hello {name}", "Greetings, {name}!");
wl(t.Transform("Hello World"))
```

**Output:**
```
Greetings, World!
```

---

### Example ID: 1080

**Description:** Demonstrates the basic difference between getting all matches and filtering for only 'focusable' ones.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Text("ID:100, Name:Admin, ID:200");

// Define two rules, but only one is marked as 'focusable'
t.Pattern("ID:{@Number}").SetFocusable(true);
t.Pattern("Name:{@Alpha}").SetFocusable(false);
t.Find();

// Get all matches using the default option
var allMatches = t.GetMatches();
wl("--- All Matches (", allMatches.Count(), ") ---")
wl(allMatches.@Text())

// Get only the focusable matches
var focusableMatches = t.GetMatches(MatchesOption::FocusableOnly);
wl("")
wl("--- Focusable Matches Only (", focusableMatches.Count(), ") ---")
wl(focusableMatches.@Text())
```

**Output:**
```
--- All Matches (3) ---
ID:100
Name:Admin
ID:200

--- Focusable Matches Only (2) ---
ID:100
ID:200
```

---

### Example ID: 1081

**Description:** Parses a log file and uses the `FocusableOnly` option to quickly extract only the critical error entries.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var log = "INFO: Task started. ERROR: Connection failed. INFO: Task finished.";
t.@Text(log);

// Rules for different log levels. Only errors are focusable.
t.Pattern("INFO: {msg}.").SetFocusable(false);
t.Pattern("ERROR: {msg}.").SetFocusable(true);
t.Find();

wl("All log entries:")
wl(t.GetMatches().@Text())
wl("")

wl("Critical errors only:")
// Use the option to filter for only the important entries
var errorMatches = t.GetMatches(MatchesOption::FocusableOnly);
wl(errorMatches.@Text())
```

**Output:**
```
All log entries:
INFO: Task started.
ERROR: Connection failed.
INFO: Task finished.

Critical errors only:
ERROR: Connection failed.
```

---

### Example ID: 1099

**Description:** A simple `Find()` followed by `@Matches().Count()` to count all occurrences of a word.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Text("apple banana apple cherry apple");

// Define a pattern to find any alphanumeric word
t.Pattern("apple");
t.Find();

wl("Found ", t.@Matches().Count(), " occurrences of 'apple'.")
```

**Output:**
```
Found 3 occurrences of 'apple'.
```

---

### Example ID: 1100

**Description:** Practical: Iterates through all matches and uses the `Match.Rule` property to identify which pattern generated each match, demonstrating a key introspection feature.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var logText = "INFO: System start. WARN: Low disk. ERROR: DB connection failed.";
t.@Text(logText);

// Define rules for different log levels
var errorRule = t.Pattern("ERROR: {msg}.");
var warnRule = t.Pattern("WARN: {msg}.");
var infoRule = t.Pattern("INFO: {msg}.");

t.Find();

wl("--- Analysis of All Matches ---")
foreach (var match in t.@Matches())
    // Use the match's Rule property to get the name of the rule that found it
    wl("Found '", match.@Text(), "' using rule: '", match.@Rule().@Name(), "'")
end foreach
```

**Output:**
```
--- Analysis of All Matches ---
Found 'INFO: System start.' using rule: 'info'
Found 'WARN: Low disk.' using rule: 'warn'
Found 'ERROR: DB connection failed.' using rule: 'error'
```

---

### Example ID: 1105

**Description:** A simple two-pass transformation where the output of the first pass becomes the input for the second.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Text("A");

// Pass 0 will change 'A' to 'B'
var pass0 = t.Pass(0);
pass0.FromTo("A", "B");

// Pass 1 will receive 'B' and change it to 'C'
var pass1 = t.Pass(1);
pass1.FromTo("B", "C");

t.Transform();
wl(t) // The final output is 'C'
```

**Output:**
```
C
```

---

### Example ID: 1118

**Description:** Shows how a full reset clears all rules and input, allowing a transformer object to be reconfigured from a clean slate.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var txt = "a b c d e";

t.@Text(txt);
t.FromTo("a", "aaa");
t.FromTo("c", "xyz");

wl("Input: ", t)
wl("Transformed: ", t.Transform())

wl("")
wl("Resetting...")
t.Reset();

wl("Input after reset: ", t, "(empty)")
t.@Text("a b c d e");
wl("New input: ", t.@Text())
wl("Transform after reset: ", t.Transform().@Text(), " (no rules exist)")

wl("")
wl("Defining new rules...")
t.FromTo("b", "ABC");
t.FromTo("d", "DDD");
wl("Final transformed: ", t.Transform().@Text())
```

**Output:**
```
Input: a b c d e
Transformed: aaa b xyz d e

Resetting...
Input after reset: (empty)
New input: a b c d e
Transform after reset: a b c d e (no rules exist)

Defining new rules...
Final transformed: a ABC c DDD e
```

---

### Example ID: 1123

**Description:** How `SkipOver` creates 'dead zones' where other rules are not applied.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Text("transform this but (not this) and this");

// A rule to replace the word 'this'
t.FromTo("this", "THAT");

// A rule to ignore any content inside parentheses
t.SkipOver("({content})");

// The 'this' inside the parentheses is protected by the SkipOver rule
wl(t.Transform())
```

**Output:**
```
transform THAT but (not this) and THAT
```

---

### Example ID: 1124

**Description:** A practical, real-world example of using `SkipOver` to ignore HTML comments while transforming other parts of the document.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Disable statement sensitivity to handle multi-line content
t.@DefaultRuleSet().@StatementSensitive(false);

var htmlContent =
[verbatim]
<nav>
  <li><a href="#intro">Intro</a></li>
  <!-- <li><a href="#contact">Contact</a></li> -->
  <li><a href="#about">About</a></li>
</nav>
[/verbatim];
t.@Text(htmlContent);

// A rule to find all list items
t.Pattern("<li>{item}</li>");

// A rule to skip over HTML comments
t.SkipOver("<!-- {comment} -->");

t.Find();
wl("--- Found List Items ---")
wl(t.@Matches().@Text())
```

**Output:**
```
--- Found List Items ---
<li><a href="#intro">Intro</a></li>
<li><a href="#about">About</a></li>
```

---

### Example ID: 1132

**Description:** A basic example of setting the text, transforming it, and retrieving the result.

**Code:**
```pseudocode
New(uCalc::Transformer, t)

// 1. Set the initial text
t.@Text("The quick brown fox.");

// 2. Define a rule and transform
t.FromTo("brown", "red");
t.Transform();

// 3. Get the final text
wl(t.@Text())
```

**Output:**
```
The quick red fox.
```

---

### Example ID: 1133

**Description:** Demonstrates using the Text property with implicit conversions (shortcuts) to parse a simple config string.

**Code:**
```pseudocode
New(uCalc::Transformer, t)

// Implicitly set the Text property by assigning a string to the object
t = "user=admin; level=9; theme=dark;";

// Define a rule to extract the user value
t.FromTo("user={name};", "Username: {name}");
t.Transform();

// Implicitly get the Text property by using the object in a string context
var(string, result) = t;
wl(result)
```

**Output:**
```
Username: admin level=9; theme=dark;
```

---

### Example ID: 1135

**Description:** Adds a C-style single-line comment token and categorizes it as whitespace to be ignored by other rules.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("this", "THAT");

var(string, text) = "transform this but not // this in a comment";

wl("--- Before --- ")
// Initially, the comment is treated as regular text.
wl(t.Transform(text))

// Add a token for C-style comments and classify it as whitespace.
t.@Tokens().Add("//.*", TokenType::Whitespace);

wl("")
wl("--- After --- ")
// Re-run the transform. The comment is now ignored.
wl(t.Transform(text))
```

**Output:**
```
--- Before --- 
transform THAT but not // THAT in a comment

--- After --- 
transform THAT but not // this in a comment
```

---

### Example ID: 1136

**Description:** Practical: Modifies the default alphanumeric token to include hyphens, allowing it to match hyphenated identifiers as single words.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@Alpha:word}", "[{word}]");
var(string, text) = "id-E123 is a special-identifier.";

wl("--- Before --- ")
// By default, 'id-123' is tokenized as three separate parts: 'id', '-', and '123'.
wl(t.Transform(text))

// Get the alphanumeric token item by its name and modify its regex.
var alphaToken = t.@Tokens()["_token_alphanumeric"];
alphaToken.@Regex("[a-zA-Z0-9-]+");

wl("")
wl("--- After --- ")
// Now, hyphenated words are matched as single alphanumeric tokens.
wl(t.Transform(text))
```

**Output:**
```
--- Before --- 
[id]-[E123] [is] [a] [special]-[identifier].

--- After --- 
[id-E123] [is] [a] [special-identifier].
```

---

### Example ID: 1138

**Description:** A simple cascading transformation (`A` -> `B` -> `C` -> `D`) shows the step-by-step output.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// RewindOnChange is necessary for cascading rules to be re-evaluated.
t.FromTo("A", "B").@RewindOnChange(true);
t.FromTo("B", "C").@RewindOnChange(true);
t.FromTo("C", "D").@RewindOnChange(true);

// Trace the transformation of "A"
var(uCalc::String, trace) = t.TraceTransform("A");

// Format the output list with ' -> ' for readability
trace.ListSeparator(" -> ");

wl(trace)
```

**Output:**
```
A -> B -> C -> D
```

---

### Example ID: 1139

**Description:** Practical: Traces the recursive expansion of a custom `MySum` function, showing how it is broken down into a standard arithmetic expression.

**Code:**
```pseudocode
var t = uc.@ExpressionTransformer();

// Assume these rules are pre-defined to create a recursive sum
t.FromTo("MySum({x})", "{x}");
t.FromTo("MySum({x}, {y})", "({x} + MySum({y}))").@RewindOnChange(true);

var(uCalc::String, trace) = t.TraceTransform("MySum(1,2,3,4)");
trace.ListSeparator([c]"\n"[/c][vb]vbCrLf[/vb]);

wl(trace)
```

**Output:**
```
MySum(1,2,3,4)
(1 + MySum(2,3,4))
(1 + (2 + MySum(3,4)))
(1 + (2 + (3 + MySum(4))))
(1 + (2 + (3 + 4)))
```

---

### Example ID: 1140

**Description:** Internal Test: Verifies advanced formatting of the trace output using `ListFormat` to create a custom, detailed step-by-step log.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("A", "B").@RewindOnChange(true);
t.FromTo("B", "C").@RewindOnChange(true);
t.FromTo("C", "D").@RewindOnChange(true);

var(uCalc::String, trace) = t.TraceTransform("A");

// Apply a custom format to each step in the list
trace.ListFormat("!", "(", ")", "$'{txt}->{n+1}/{c}'", "txt", "n", "c");

wl(trace)
```

**Output:**
```
(A->1/4!B->2/4!C->3/4!D->4/4)
```

---

### Example ID: 1141

**Description:** A simple find-and-replace transformation to replace all occurrences of a word.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Define a simple replacement rule
t.FromTo("Hello", "Greetings");

// Execute the transformation on an input string
t.@Text("Hello World, and Hello again.");
wl(t.Transform())
```

**Output:**
```
Greetings World, and Greetings again.
```

---

### Example ID: 1142

**Description:** A practical example sanitizing user input by removing script tags and normalizing excess whitespace in a single pass.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Rule 1: Remove script tags and their content (case-insensitive, multi-line)
t.FromTo("<script>{content}</script>", "");
t.@DefaultRuleSet().SetCaseSensitive(false).SetStatementSensitive(false);

// Rule 2: Normalize one or more whitespace characters to a single space
t.FromTo("{@Whitespace:ws}", " ");

// Transform the input in one go and print the result
t.@Text("  Welcome!  <SCRIPT>alert('bad');</SCRIPT>Please enjoy.  ");
wl("Sanitized: '", t.Transform(), "'")
```

**Output:**
```
Sanitized: ' Welcome! Please enjoy. '
```

---

### Example ID: 1144

**Description:** A simple find-and-replace transformation to replace all occurrences of a word.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
// Define a simple replacement rule
t.FromTo("Hello", "Greetings");

// Execute the transformation on an input string
wl(t.Transform("Hello World, and Hello again."))
End Using
```

**Output:**
```
Greetings World, and Greetings again.
```

---

### Example ID: 1145

**Description:** A practical example sanitizing user input by removing script tags and normalizing excess whitespace in a single pass.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
// Rule 1: Remove script tags and their content (case-insensitive, multi-line)
t.FromTo("<script>{content}</script>", "");
t.@DefaultRuleSet().SetCaseSensitive(false).SetStatementSensitive(false);

// Rule 2: Normalize one or more whitespace characters to a single space
t.FromTo("{@Whitespace:ws}", " ");
        
var(string, userInput) = "  Welcome!  <SCRIPT>alert('bad');</SCRIPT>Please enjoy.  ";
        
// Transform the input in one go and print the result
wl("Sanitized: '", t.Transform(userInput), "'")
End Using
```

**Output:**
```
Sanitized: ' Welcome! Please enjoy. '
```

---

### Example ID: 1150

**Description:** Demonstrates the basic true/false state of the WasModified flag.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("a", "*a good*");

// Case 1: A match occurs, text is modified.
t.@Text("This is a test");
t.Transform();
wl("Modified: ", bool(t.@WasModified()))

// Case 2: No match occurs, text is unchanged.
t.@Text("This is another test");
t.Transform();
wl("Modified: ", bool(t.@WasModified()))
```

**Output:**
```
Modified: True
Modified: False
```

---

### Example ID: 1151

**Description:** Shows how to use WasModified to avoid an expensive operation, like saving to a file, if no changes were made during a data sanitization process.

**Code:**
```pseudocode
New(uCalc::Transformer, sanitizer)
sanitizer.FromTo("error", "ERROR");

// Simulate processing multiple logs
var(string, log1) = "status: ok";
var(string, log2) = "status: error";

wl("--- Processing Log 1 ---")
sanitizer.@Text(log1);
sanitizer.Transform();
if (sanitizer.@WasModified())
    wl("Change detected. Saving updated log...")
    // SaveToFile(sanitizer.GetText());
else
    wl("No changes. Skipping save.")
end if

wl("")
wl("--- Processing Log 2 ---")
sanitizer.@Text(log2);
sanitizer.Transform();
if (sanitizer.@WasModified())
    wl("Change detected. Saving updated log...")
    // SaveToFile(sanitizer.GetText());
    wl("Updated log: ", sanitizer.@Text())
else
    wl("No changes. Skipping save.")
end if
```

**Output:**
```
--- Processing Log 1 ---
No changes. Skipping save.

--- Processing Log 2 ---
Change detected. Saving updated log...
Updated log: status: ERROR
```

---

### Example ID: 1156

**Description:** A simple find-and-replace operation using the fluent, chainable API.

**Code:**
```pseudocode
NewUsing(uCalc::String, s("The quick brown fox."))

// Replace returns the modified String object
s.Replace("brown", "red");

// Use implicit conversion to print the result
wl(s)
End Using
```

**Output:**
```
The quick red fox.
```

---

### Example ID: 1159

**Description:** Demonstrates interoperability between `Transformer` and `String` objects, and chaining methods to create nested views.

**Code:**
```pseudocode
// Create a transformer and perform a transformation
var t = uc.NewTransformer();
t.@Text("if (x > 3) y = x * 2; else if(x == 5) y = x - 1;");
t.FromTo("1", "100");
t.Transform();

// --- Interoperability and Chaining ---

var Pattern = "if ({cond})";

// 1. Create a uCalc.String from a Transformer.
// 2. Chain .After() to get a "live view" of the text after the pattern.
New(uCalc::String, s(t))
var after_first_if = s.After(Pattern);
wl(after_first_if.@Text())

// 3. Chain another .After() on the child string.
var after_second_if = after_first_if.After(Pattern);
wl(after_second_if.@Text())

// --- String to Transformer Conversion ---

// 4. Create a uCalc.String and assign it text.
New(uCalc::String, s2)
s2 = "This is a test";

// 5. Create a Transformer from the uCalc.String to use transformer-specific methods.
New(uCalc::Transformer, t2(s2))
wl(t2.@Text())
```

**Output:**
```
y = x * 2; else if(x == 5) y = x - 100;
 y = x - 100;
This is a test
```

---

### Example ID: 1160

**Description:** Demonstrates the basic getter and setter syntax for a property

**Code:**
```pseudocode
New(uCalc::Transformer, t)

// Set the description using the property setter syntax
t.@Description("My Transformer");

// Get the description using the property getter syntax
wl("Description: ", t.@Description())
```

**Output:**
```
Description: My Transformer
```

---

### Example ID: 1161

**Description:** A practical example using the fluent interface of `Set...` methods to configure multiple properties of a rule in a single chained statement.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var rule = t.FromTo("A", "B");

// Chain multiple Set... methods for a clean configuration
rule.SetCaseSensitive(true)[c]
    [/c].SetWhitespaceSensitive(false)[c]
    [/c].SetQuoteSensitive(false);

// Verify the properties were set using their corresponding getters
wl("Case Sensitive: ", bool(rule.@CaseSensitive()))
wl("Whitespace Sensitive: ", bool(rule.@WhitespaceSensitive()))
wl("Quote Sensitive: ", bool(rule.@QuoteSensitive()))
```

**Output:**
```
Case Sensitive: True
Whitespace Sensitive: False
Quote Sensitive: False
```

---

### Example ID: 1163

**Description:** Extracting a value from a simple key-value pair.

**Code:**
```pseudocode
NewUsing(uCalc::String, s("ID: 12345"))

// Get the text after the "ID: " prefix
var value = s.After("ID: ");

wl(value)
End Using
```

**Output:**
```
 12345
```

---

### Example ID: 1164

**Description:** A practical example demonstrating how to extract an error message from a log entry and then chain another operation on the result.

**Code:**
```pseudocode
NewUsing(uCalc::String, log("INFO: Task complete. ERROR: File not found."))

// Chain After() to isolate the error, then Replace() to modify it.
var errorDetails = log.After("ERROR: ").Replace("File", "Resource");

wl("Original log: ", log)      // The original string is modified in-place
wl("Modified details:", errorDetails) // The view reflects the change
End Using
```

**Output:**
```
Original log: INFO: Task complete. ERROR: Resource not found.
Modified details: Resource not found.
```

---

### Example ID: 1165

**Description:** Internal Test: Verifies behavior for patterns at the end of the string and patterns that are not found.

**Code:**
```pseudocode
NewUsing(uCalc::String, s("A B C"))

// Case 1: Pattern is at the end. Should return an empty string.
w("After 'C': '")
w(s.After("C"))
wl("'")

// Case 2: Pattern does not exist. Should return an empty string.
w("After 'D': '")
w(s.After("D"))
wl("'")

// Case 3: Get text after the first word.
w("After 'A': '")
w(s.After("A"))
wl("'")
End Using
```

**Output:**
```
After 'C': ''
After 'D': ''
After 'A': ' B C'
```

---

### Example ID: 1172

**Description:** Demonstrates the power of token-awareness by safely renaming a variable while ignoring its name inside a string literal—a common failure point for character-based Regex.

**Code:**
```pseudocode
New(uCalc::Transformer, t)

// A snippet of code where 'rate' is both a variable and part of a string
var source_code = [verbatim]rate = 0.05; // Set default rate
print("Current rate is: " + rate);[/verbatim];

wl("Original Code:")
wl(source_code)
wl("")

// Define a rule to rename the VARIABLE 'rate' to 'annual_rate'
t.FromTo("rate", "annual_rate");
t.SkipOver("// {text}");

// Run the transformation. The 'rate' inside the string is untouched.
wl("Transformed Code:")
wl(t.Transform(source_code))
```

**Output:**
```
Original Code:
rate = 0.05; // Set default rate
print("Current rate is: " + rate);

Transformed Code:
annual_rate = 0.05; // Set default rate
print("Current rate is: " + annual_rate);
```

---

### Example ID: 1173

**Description:** Demonstrates how uCalc's token-aware Transformer safely renames a variable without corrupting a string literal, a common failure point for Regex.

**Code:**
```pseudocode
New(uCalc::Transformer, t)

// A rule to replace the alphanumeric token 'x' with 'value'
t.FromTo("x", "value");

// The input string where 'x' appears both as a variable and inside a string
var code = [verbatim]if (x > 10) print("Max value is x");[/verbatim];

// The transformation correctly ignores the 'x' inside the quoted string
wl(t.Transform(code))
```

**Output:**
```
if (value > 10) print("Max value is x");
```

---

### Example ID: 1175

**Description:** Illustrates lazy evaluation by creating a custom 'Repeat' function that executes a code block (passed with `ByExpr`) a specified number of times.

**Code:**
```pseudocode
[head]
[callback MyRepeat]
  var count = cb.ArgInt32(1);
  var action = cb.ArgExpr(2);

  for(int i = 1 to count)
    action.Execute(); // Evaluate the passed-in expression
  end for
[/callback]

[body]
// Define a variable that our action will modify
uc.DefineVariable("counter = 0");

// Define the function. The 'action' parameter is marked with ByExpr
// to ensure it's passed as an unevaluated expression object.
uc.DefineFunction("Repeat(count As Int, ByExpr action)", MyRepeat);

// Call the custom Repeat function. The expression 'counter++' is not
// evaluated here; it's passed to the callback to be executed in a loop.
uc.Eval("Repeat(5, counter++)");

// Verify the side effect
wl("Final counter value: ", uc.Eval("counter"))
```

**Output:**
```
Final counter value: 5
```

---

### Example ID: 1176

**Description:** A 'Hello, World!' example demonstrating the creation and evaluation of an expression using the modern, simplified syntax.

**Code:**
```pseudocode
// Create a new Expression object with an initial formula.
// This uses the default uCalc instance for context.
New(uCalc::Expression, expr("1 + 1"))

// Implicitly calls .EvaluateStr() when used in a string context
wl("Initial value: ", expr)

// Reassign the expression to a new formula with a simple string assignment.
// This implicitly calls .Parse() behind the scenes.
expr = "10 * (5 + 3)";

// Retrieve the result. For numeric results, you can assign it
// directly to a double. This implicitly calls .Evaluate().
var(double, result) = expr;
w("New value: ", result)
```

**Output:**
```
Initial value: 2
New value: 80
```

---

### Example ID: 1177

**Description:** Evaluating a basic arithmetic expression with multiple operators.

**Code:**
```pseudocode
wl(uc.EvalStr("10 * 5 + 3"))
```

**Output:**
```
53
```

---

### Example ID: 1178

**Description:** Calculating a simple percentage for a real-world financial scenario.

**Code:**
```pseudocode
// Calculate a 15% discount on a price of $75
w("Discounted price: ")
wl(uc.EvalStr("75 * (1 - 0.15)"))
```

**Output:**
```
Discounted price: 63.75
```

---

### Example ID: 1179

**Description:** Internal Test: Verify correct order of operations with mixed operators and parentheses.

**Code:**
```pseudocode
// This tests the precedence of power (^), multiplication (*), and addition (+).
// The correct evaluation is 5 + (2 * (3^2)) -> 5 + (2 * 9) -> 5 + 18 -> 23.
wl(uc.EvalStr("5 + 2 * 3^2"))
```

**Output:**
```
23
```

---

### Example ID: 1180

**Description:** A basic example of defining a variable and using it in an expression.

**Code:**
```pseudocode
uc.DefineVariable("x = 10");
wl(uc.EvalStr("x * 5"))
```

**Output:**
```
50
```

---

### Example ID: 1181

**Description:** Calculates simple interest using pre-defined variables for a real-world scenario.

**Code:**
```pseudocode
uc.DefineVariable("principal = 5000");
uc.DefineVariable("rate = 0.05");
uc.DefineVariable("years = 4");
wl("Interest: ", uc.EvalStr("principal * rate * years"))
```

**Output:**
```
Interest: 1000
```

---

### Example ID: 1182

**Description:** Internal Test: Tests programmatic updates to a variable from host code in a loop, a common high-performance pattern.

**Code:**
```pseudocode
var myVar = uc.DefineVariable("x");
var expr = uc.Parse("x * 2");

var i = 0;
for (i = 1 to 5)
  myVar.Value(i);
  wl("When x is ", i, ", result is: ", expr.Evaluate())
end for
```

**Output:**
```
When x is 1, result is: 2
When x is 2, result is: 4
When x is 3, result is: 6
When x is 4, result is: 8
When x is 5, result is: 10
```

---

### Example ID: 1183

**Description:** A simple example demonstrating a few of the most common math, logic, and string functions.

**Code:**
```pseudocode
wl("Square root of 81 is: ", uc.Eval("Sqrt(81)"))
wl("Is 10 greater than 5? ", uc.EvalStr("IIf(10 > 5, 'Yes', 'No')"))
wl("String length: ", uc.Eval("Length('uCalc rocks!')"))
```

**Output:**
```
Square root of 81 is: 9
Is 10 greater than 5? Yes
String length: 12
```

---

### Example ID: 1185

**Description:** Internal Test: Verifies that a built-in function using `ByHandle` arguments can correctly modify the state of variables passed to it.

**Code:**
```pseudocode
uc.DefineVariable("a = 10");
uc.DefineVariable("b = 20");

wl("Before - a: ", uc.Eval("a"), ", b: ", uc.Eval("b"))

// The built-in Swap() function uses ByHandle to modify variables directly.
uc.Eval("Swap(a, b)");

w("After - a: ", uc.Eval("a"), ", b: ", uc.Eval("b"))
```

**Output:**
```
Before - a: 10, b: 20
After - a: 20, b: 10
```

---

### Example ID: 1186

**Description:** A simple inline function to convert inches to centimeters.

**Code:**
```pseudocode
uc.DefineFunction("InToCm(inches) = inches * 2.54");
wl(uc.Eval("InToCm(10)"))
```

**Output:**
```
25.4
```

---

### Example ID: 1187

**Description:** Practical: A callback-based logging function that prints a message to the console.

**Code:**
```pseudocode
[head]
[callback LogMessage]
  var(string, msg) = cb.ArgStr(1);
  // In a real app, this would write to a file or log service.
  wl("[LOG]: " + msg)
[/callback]
[body]
uc.DefineFunction("Log(message As String)", LogMessage);
uc.Eval("Log('System initialized')");
uc.Eval("Log('User logged in')");
```

**Output:**
```
[LOG]: System initialized
[LOG]: User logged in
```

---

### Example ID: 1188

**Description:** Internal Test: A custom `IIf` implementation using `ByExpr` to test lazy evaluation. The branches containing division by zero are never executed, preventing errors.

**Code:**
```pseudocode
[head]
[callback CustomIIf]
  var(bool, condition) = cb.ArgBool(1);
  var truePart = cb.ArgExpr(2);
  var falsePart = cb.ArgExpr(3);
  
  if (condition)
    cb.Return(truePart.Evaluate());
  else
    cb.Return(falsePart.Evaluate());
  end if
[/callback]
[body]
uc.DefineFunction("MyIIf(condition As Bool, ByExpr thenExpr, ByExpr elseExpr)", CustomIIf);

// The 'else' branch contains a division by zero, but it should NOT be evaluated
// because the condition (1 < 2) is true.
var result = uc.Eval("MyIIf(1 < 2, 100, 1/0)");
w("Result 1: ")
wl(result)

// Now test the false branch. The 'then' branch with the error is skipped.
result = uc.Eval("MyIIf(1 > 2, 1/0, 200)");
w("Result 2: ")
wl(result)
```

**Output:**
```
Result 1: 100
Result 2: 200
```

---

### Example ID: 1189

**Description:** How to reactively check for an error after an operation fails, and how a subsequent successful operation clears the error state.

**Code:**
```pseudocode
// Trigger a syntax error
uc.EvalStr("1 +");

// Check the error state after the fact
if (uc.@Error().@Code() != ErrorCode::None)
    wl("Error detected: ", uc.@Error().@Message())
else 
    wl("Success!")
end if

// Perform a successful operation, which clears the error state
uc.EvalStr("1 + 1");
if (uc.@Error().@Code() == ErrorCode::None)
    wl("Previous error was cleared by successful operation.")
end if
```

**Output:**
```
Error detected: Syntax error
Previous error was cleared by successful operation.
```

---

### Example ID: 1190

**Description:** A practical example of a proactive error handler that automatically defines undeclared variables on the fly, allowing the expression to successfully resume execution.

**Code:**
```pseudocode
[head]
// This handler automatically defines variables when they are first used.
[callback:u AutoDefineHandler]
  // Check if the error is specifically an undefined identifier
  if (uc.@Error().@Code() == ErrorCode::Undefined_Identifier)
    wl("Handler: '", uc.@Error().@Symbol(), "' is undefined. Defining it now.")
    uc.DefineVariable(uc.@Error().@Symbol());
    
    // Tell the engine to resume the operation
    uc.@Error().@Response(ErrorHandlerResponse::Resume);
  end if
[/callback]

[body]
uc.@Error().AddHandler(AutoDefineHandler);

// 'my_var' doesn't exist yet, but the handler will create it.
var result = uc.EvalStr("my_var = 100; my_var = my_var * 2");

wl("Final result: ", result)
```

**Output:**
```
Handler: 'my_var' is undefined. Defining it now.
Final result: 200
```

---

### Example ID: 1192

**Description:** A minimal example demonstrating the basic 'Parse once, Evaluate many' pattern.

**Code:**
```pseudocode
// 1. Parse the expression string once to create a reusable object.
//var expr = uc.Parse("5 * 10");
NewUsing(uCalc::Expression, expr("5 * 10"))

// 2. Evaluate the pre-parsed object as many times as needed.
wl(expr.Evaluate())
wl(expr.Evaluate())

End Using // The expression object is automatically released here.
```

**Output:**
```
50
50
```

---

### Example ID: 1193

**Description:** A real-world example contrasting the inefficient loop with the high-performance 'Parse-Once' pattern using a changing variable.

**Code:**
```pseudocode
var x_var = uc.DefineVariable("x");
var i = 0;

// --- Inefficient Way ---
wl("--- Inefficient: Eval() in a loop ---")
for (i = 1 to 3)
    x_var.Value(i);
    wl(uc.Eval("x * x + 2"))
end for

wl("")

// --- High-Performance Way ---
wl("--- Efficient: Parse() once, Evaluate() in a loop ---")
// Parse outside the loop
var expr = uc.Parse("x * x + 2");
for (i = 1 to 3)
    x_var.Value(i);
    // Evaluate the pre-parsed object
     wl(expr.Evaluate())
end for
```

**Output:**
```
--- Inefficient: Eval() in a loop ---
3
6
11

--- Efficient: Parse() once, Evaluate() in a loop ---
3
6
11
```

---

### Example ID: 1194

**Description:** Internal Test: Verifies correct results with multiple variables and a function call within a tight loop using a pre-parsed expression.

**Code:**
```pseudocode
uc.DefineFunction("Calc(a, b) = a * 2 - b");
var x_var = uc.DefineVariable("x");
var y_var = uc.DefineVariable("y");
var i = 0;

var expr = uc.Parse("Calc(x, y) + Sqrt(x)");
for (i = 1 to 4)
    x_var.Value(i * i); // Use squared values for x
    y_var.Value(i);     // Use linear values for y
    wl(expr.Evaluate())
end for
```

**Output:**
```
2
8
18
32
```

---

### Example ID: 1195

**Description:** A basic find-and-replace operation to change one word to another using a fluent, chainable syntax.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)

// Define the rule and execute the transform in a single, chained statement.
   t.FromTo("Hello", "Greetings");
   wl(t.Transform("Hello World!"))

End Using
```

**Output:**
```
Greetings World!
```

---

### Example ID: 1196

**Description:** Safely renames a variable without corrupting a string literal, demonstrating the Transformer's token-awareness.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)

// This rule replaces the ALPHANUMERIC token 'x', not just the character 'x'.
t.FromTo("x", "value");

var code = [verbatim]if (x > 10) print("Max value is x");[/verbatim];

// The 'x' inside the string is ignored because QuoteSensitive is true by default.
wl(t.Transform(code))

End Using
```

**Output:**
```
if (value > 10) print("Max value is x");
```

---

### Example ID: 1198

**Description:** Extracts a value from a simple key-value pair.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("ID: {value}", "Found value: {value}");
wl(t.Transform("Product ID: 12345"))
```

**Output:**
```
Product Found value: 12345
```

---

### Example ID: 1199

**Description:** Parses a structured log entry and reformats it for display using multiple variables.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Note the use of {@String} to capture the quoted text
t.FromTo("'['{level}']' Code: {code}, Msg: {@String:message}",
         "[{level}] - {message} (Code {code})");

var log = "[ERROR] Code: 404, Msg: 'Not Found'";
wl(t.Transform(log))
```

**Output:**
```
[ERROR] - Not Found (Code 404)
```

---

### Example ID: 1201

**Description:** A simple example demonstrating how to find and wrap all numeric values in a string.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Define a rule to find any number and wrap it in 'Num(...)'
t.FromTo("{@Number:n}", "Num({n})");

wl(t.Transform("var x = 10.5; var y = 20;"))
```

**Output:**
```
var x = Num(10.5); var y = Num(20);
```

---

### Example ID: 1204

**Description:** A basic pattern demonstrating how an optional word affects the match.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("Log [ERROR] entry", "MATCHED");

// This matches because the optional word is present
wl(t.Transform("Log ERROR entry found."))

// This also matches because the word is optional
wl(t.Transform("Log entry found."))
```

**Output:**
```
MATCHED found.
MATCHED found.
```

---

### Example ID: 1205

**Description:** Parses log entries to extract an optional error code, providing a default status when it's missing by using the `{!var:...}` fallback syntax.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Pattern: Match "Log:", an optional level, and the message.
// Replacement: Use `{!level:INFO}` to insert 'INFO' if {level} is empty.
t.FromTo("Log: [{level: ERROR | WARN}] {msg}", 
         "Status:{!level:INFO}{level} | Msg:{msg}");

// Case 1: Level is present
wl(t.Transform("Log: ERROR File not found"))

// Case 2: Level is missing, so the fallback is used
wl(t.Transform("Log: System started successfully"))
```

**Output:**
```
Status:ERROR | Msg:File not found
Status:INFO | Msg:System started successfully
```

---

### Example ID: 1207

**Description:** How to match one of several possible status keywords.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("Status: { OK | Error | Pending }", "Found Valid Status");

wl(t.Transform("Status: OK"))
wl(t.Transform("Status: Error"))
wl(t.Transform("Status: Fail"))
```

**Output:**
```
Found Valid Status
Found Valid Status
Status: Fail
```

---

### Example ID: 1210

**Description:** A basic example demonstrating how to ignore a block of text in parentheses, preventing other rules from matching inside it.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("word", "WORD"); // Rule to uppercase 'word'
t.SkipOver("({ignore})"); // Rule to ignore content in parentheses

var text = "transform this word, but (not this word)";
wl(t.Transform(text))
```

**Output:**
```
transform this WORD, but (not this word)
```

---

### Example ID: 1217

**Description:** Performing a simple unit conversion from inches to centimeters using `{@Eval}`.

**Code:**
```pseudocode
New(uCalc::Transformer, t)

// Capture a number followed by 'in' and convert it.
// Note: `len` is a string, so we must use Double(len) for the calculation.
t.FromTo("{@Number:len}in", "{@Eval: Double(len) * 2.54}cm");

wl(t.Transform("The board is 10in long."))
```

**Output:**
```
The board is 25.4cm long.
```

---

### Example ID: 1218

**Description:** A practical example that calculates line-item totals for a list of products by capturing quantity and price.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Rule to find quantity and price, then calculate total.
// Note the explicit Double() to convert the captured numerical
// values as text into double-precision numbers for {@Eval}.
t.FromTo("Qty: {@Number:qty}, Price: {@Number:price}", 
         "{@Self}, Total: {@Eval: Double(qty) * Double(price)}");

var invoice = [verbatim]Item: Book, Qty: 3, Price: 15.00
Item: Pen, Qty: 10, Price: 1.50[/verbatim];

wl(t.Transform(invoice))
```

**Output:**
```
Item: Book, Qty: 3, Price: 15.00, Total: 45
Item: Pen, Qty: 10, Price: 1.50, Total: 15
```

---

### Example ID: 1220

**Description:** Internal Test: Verifies that `{@@Eval}` can correctly parse and evaluate an expression that is itself captured from the text.

**Code:**
```pseudocode
New(uCalc::Transformer, t)

// The variable {formula} will capture the literal text "10 * (5-2)".
// {@@Eval} then executes that text as an expression.
t.FromTo("solve({formula})", "'{formula}' is {@@Eval: formula}.");

var text = "The answer to solve(10 * (5-2))";
wl(t.Transform(text))
```

**Output:**
```
The answer to '10 * (5-2)' is 30.
```

---

### Example ID: 1223

**Description:** Internal Test: Implements C-style hexadecimal literals (e.g., 0xFF) by adding a new token rule and a token transformation.

**Code:**
```pseudocode
// 1. Define the lexical rule.
// The regex matches '0x' followed by hex digits.
// The TokenType::TokenTransform tells the parser to pre-process this token.
uc.@ExpressionTokens().Add("0x[0-9a-fA-F]+", TokenType::TokenTransform);

// 2. Define the transformation rule.
// This captures the hex digits and replaces the whole token with a call to BaseConvert.
uc.@TokenTransformer().FromTo("{'0x'}{val:'[0-9a-fA-F]+'}", "BaseConvert('{val}', 16)");

// 3. Now, the new literal format can be used in expressions.
wl(uc.Eval("0xFF + 0xA")) // 255 + 10
wl(uc.EvalStr("Hex(0x100)")) // Hex(256)
```

**Output:**
```
265
100
```

---

### Example ID: 1224

**Description:** Defines a custom `sum_to` operator to calculate the sum of a numeric range, demonstrating a single-word operator.

**Code:**
```pseudocode
// Define the variables that the operator's expression will use.
uc.DefineVariable("i");
uc.DefineVariable("total");

// Define a new 'sum_to' operator at runtime, with precedence level of 50.
// It uses the built-in ForLoop function to sum numbers into the 'total' variable.
uc.DefineOperator("{start} sum_to {end} = total = 0; ForLoop(i, start, end, 1, total = total + i)", 50);

// Use the new operator. The result is stored in the 'total' variable.
uc.Eval("1 sum_to 5");

wl("The sum from 1 to 5 is: ", uc.Eval("total"))
```

**Output:**
```
The sum from 1 to 5 is: 15
```

---

### Example ID: 1225

**Description:** Creates a domain-specific currency conversion syntax using the ExpressionTransformer, the correct tool for multi-word patterns.

**Code:**
```pseudocode
// 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})");

wl("100 USD is approx. ", uc.EvalStr("100 USD to EUR"), " EUR")
wl("120 EUR is approx. ", uc.EvalStr("120 EUR to USD"), " USD")
```

**Output:**
```
100 USD is approx. 92.00 EUR
120 EUR is approx. 130.43 USD
```

---

### Example ID: 1226

**Description:** A simple demonstration of safely renaming a variable without corrupting a string literal, a common pitfall for Regex.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// This rule only targets the alphanumeric token 'x'.
t.FromTo("x", "value");
var code = [verbatim]x = 5; print("The value of x is...");[/verbatim];
wl(t.Transform(code))
```

**Output:**
```
value = 5; print("The value of x is...");
```

---

### Example ID: 1227

**Description:** A real-world refactoring task to rename a function, showing how uCalc correctly ignores matches inside comments and strings by default.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// This rule replaces the ALPHANUMERIC token 'get_data', not just the text.
t.FromTo("get_data", "fetch_records");

var code = [verbatim]
// Note: 'get_data' is the old function name.
results = get_data(source);
print("The 'get_data' function was called.");
[/verbatim];

// The default tokenizer recognizes the comment and string literal as separate tokens,
// so the rule to replace the function name doesn't affect them.
wl(t.Transform(code))
```

**Output:**
```
// Note: 'get_data' is the old function name.
results = fetch_records(source);
print("The 'get_data' function was called.");
```

---

### Example ID: 1228

**Description:** Internal Test: Contrasts a token-aware uCalc replacement with a character-aware regex replacement to highlight safety.

**Code:**
```pseudocode
var code = [verbatim]rate = 0.05; print("rate"); // a rate[/verbatim];

wl("--- uCalc Transformer (Token-Aware & Correct) ---")
New(uCalc::Transformer, t)
t.@Tokens().Add("//.*", TokenType::Whitespace);
// Rule targets only the alphanumeric token 'rate'
t.FromTo("rate", "annual_rate");
wl(t.Transform(code))

wl("")
wl("--- Simulated Regex (Character-Aware & Incorrect) ---")
// This simulates a simple find-and-replace for the word 'rate'
// which incorrectly changes the string literal and comment.
var incorrect_result = [verbatim]annual_rate = 0.05; print("annual_rate"); // a annual_rate[/verbatim];
wl(incorrect_result)
```

**Output:**
```
--- uCalc Transformer (Token-Aware & Correct) ---
annual_rate = 0.05; print("rate"); // a rate

--- Simulated Regex (Character-Aware & Incorrect) ---
annual_rate = 0.05; print("annual_rate"); // a annual_rate
```

---

### Example ID: 1229

**Description:** Creates a custom `IIf` function to demonstrate basic lazy evaluation. The division-by-zero error in the unevaluated branch is safely ignored.

**Code:**
```pseudocode
[head]
[callback MyIIf]
  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());
  end if
[/callback]
[body]
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.
wl(uc.Eval("MyIIf(10 > 5, 100, 1/0)"))

// The 'then' branch contains 1/0, but it is never evaluated.
wl(uc.Eval("MyIIf(10 < 5, 1/0, 200)"))
```

**Output:**
```
100
200
```

---

### Example ID: 1230

**Description:** Practical: Builds a custom `Repeat` loop control structure that executes an action a specified number of times.

**Code:**
```pseudocode
[head]
[callback MyRepeat]
  var count = cb.ArgInt32(1);
  var action = cb.ArgExpr(2);
  var i = 0;
  for(i = 1 to count)
    action.Execute(); // Evaluate the expression on each iteration
  end for
[/callback]
[body]
// Define a counter variable in the engine
uc.DefineVariable("counter = 0");

// The action 'counter++' is passed as an unevaluated expression
uc.DefineFunction("Repeat(count As Int, ByExpr action)", MyRepeat);

// Execute the custom loop
uc.Eval("Repeat(5, counter++)");

w("Final counter value: ")
wl(uc.Eval("counter"))
```

**Output:**
```
Final counter value: 5
```

---

### Example ID: 1231

**Description:** Internal Test: Implements a `ShortCircuitOr` function to prove that the second argument is not evaluated if the first is true, using side effects (counters) for verification.

**Code:**
```pseudocode
[head]
[callback ShortCircuitOr]
  var arg1 = cb.ArgExpr(1);
  var arg2 = cb.ArgExpr(2);

  // Evaluate the first argument
  var result1 = arg1.EvaluateBool();

  // If the first is true, return immediately without touching the second
  if (result1)
    cb.ReturnBool(true);
  else
    // Otherwise, evaluate and return the second argument's result
    cb.ReturnBool(arg2.EvaluateBool());
  end if
[/callback]

[callback FuncA]
  cb.@uCalc().Eval("countA = countA + 1");
  cb.ReturnBool(true);
[/callback]

[callback FuncB]
  cb.@uCalc().Eval("countB = countB + 1");
  cb.ReturnBool(true);
[/callback]

[body]
uc.DefineVariable("countA = 0");
uc.DefineVariable("countB = 0");

uc.DefineFunction("FuncA() As Bool", FuncA);
uc.DefineFunction("FuncB() As Bool", FuncB);

uc.DefineFunction("SC_Or(ByExpr a, ByExpr b) As Bool", ShortCircuitOr);

wl("Calling SC_Or(FuncA(), FuncB())...")
uc.Eval("SC_Or(FuncA(), FuncB())");

wl("FuncA was called ", uc.Eval("countA"), " time(s).")
wl("FuncB was called ", uc.Eval("countB"), " time(s).") // Should be 0
```

**Output:**
```
Calling SC_Or(FuncA(), FuncB())...
FuncA was called 1 time(s).
FuncB was called 0 time(s).
```

---

### Example ID: 1236

**Description:** A simple `Describe` function that uses `ByHandle` to inspect an argument's name and data type.

**Code:**
```pseudocode
[head]
[callback DescribeArg]
  // Retrieve the Item object for the first argument.
  var item = cb.ArgItem(1);

  // Inspect the item's metadata.
  var name = item.@Name();
  if ([c]name == ""[/c][vb]Len(name) == 0[/vb])
    name = "(literal)";
  end if

  wl("  - Name: ", name, ", Type: ", item.@DataType().@Name());
[/callback]
[body]
uc.DefineFunction("Describe(ByHandle arg As AnyType)", DescribeArg);
uc.DefineVariable("my_var = 100");

wl("Inspecting a variable:")
uc.Eval("Describe(my_var)");

wl("Inspecting a literal value:")
uc.Eval("Describe(123.45)");

wl("Inspecting a string value:")
uc.EvalStr("Describe('abc xyz')");
```

**Output:**
```
Inspecting a variable:
  - Name: my_var, Type: double
Inspecting a literal value:
  - Name: (literal), Type: double
Inspecting a string value:
  - Name: (literal), Type: string
```

---

### Example ID: 1237

**Description:** A practical, generic `Print` function that can accept any number of arguments of any type and display them in a formatted string.

**Code:**
```pseudocode
[head]
[callback PrintGeneric]
  var(string, output) = "";
  var i = 0;
  for (i = 1 to cb.ArgCount())
    // Get the item and retrieve its value as a string.
    var item = cb.ArgItem(i);
    output = output + item.ValueStr();
    if (i < cb.ArgCount())
      output = output + ", ";
    end if
  end for
  wl(output)
[/callback]
[body]
// Define a variadic function that accepts any number of arguments ByHandle.
uc.DefineFunction("Print(ByHandle args As AnyType...)", PrintGeneric);

uc.Eval("Print('User:', 'Alice', 'ID:', 101, 'Status:', true)");
```

**Output:**
```
User:, Alice, ID:, 101, Status:, true
```

---

### Example ID: 1239

**Description:** A simple demonstration of finding a word but only inside a specific parenthetical block.

**Code:**
```pseudocode
New(uCalc::Transformer, t)

// 1. Parent rule finds content inside parentheses.
var parentRule = t.FromTo("({body})", "({body})");

// 2. Get the local transformer for the parent.
var local_t = parentRule.@LocalTransformer();

// 3. Child rule runs only inside the parentheses.
local_t.FromTo("this", "THIS");

var text = "do not find this, but (find this) and not this";
wl(t.Transform(text))
```

**Output:**
```
do not find this, but (find THIS) and not this
```

---

### Example ID: 1240

**Description:** A practical example that extracts all `<a>` tags, but only from within a specific `<nav>` section of an HTML document.

**Code:**
```pseudocode
var t = uc.NewTransformer();

// Ignore multi-line formatting
t.@DefaultRuleSet().@StatementSensitive(false);

// 1. Parent rule captures the content of the <nav> block.
var navRule = t.Pattern("<nav>{content}</nav>");

// 2. Get the local transformer for the nav block.
var local_t = navRule.@LocalTransformer();

// 3. This rule will only find `<a>` tags inside the <nav> block.
local_t.Pattern("<a href={url}>{text}</a>");

var html = [verbatim]<nav>
  <a href="/home">Home</a>
  <a href="/about">About</a>
</nav>
<main>
  <p>Some text with another <a href="/other">other link</a>.</p>
</main>[/verbatim];

t.@Text(html);
t.Find();

wl("--- Found Links (Innermost Matches Only) ---")
// Use InnermostOnly to see only the results from the local transformer.
wl(t.GetMatches(MatchesOption::InnermostOnly).@Text())
```

**Output:**
```
--- Found Links (Innermost Matches Only) ---
<a href="/home">Home</a>
<a href="/about">About</a>
```

---

### Example ID: 1242

**Description:** Defines a simple `Add` function that is implemented by a native callback to perform addition.

**Code:**
```pseudocode
[head]
[callback MyAdd]
  var x = cb.Arg(1);
  var y = cb.Arg(2);
  cb.Return(x + y);
[/callback]
[body]
// Link the uCalc function 'Add' to the native 'MyAdd' callback.
uc.DefineFunction("Add(x, y)", MyAdd);

// Now the native code can be called from an expression.
wl(uc.Eval("Add(10, 5)"))
```

**Output:**
```
15
```

---

### Example ID: 1243

**Description:** Demonstrates a practical callback that retrieves a 'host application setting', simulating I/O or access to native configuration.

**Code:**
```pseudocode
[head]
[callback GetSetting]
  // Get the name of the setting to retrieve.
  var settingName = cb.ArgStr(1);
  
  // In a real app, this would read from a config file, database, or registry.
  // We simulate it by evaluating another variable in the parent uCalc context.
  var value = cb.@uCalc().EvalStr(settingName);
  
  cb.ReturnStr(value);
[/callback]
[body]
// Simulate a host application's configuration store using uCalc variables.
uc.DefineVariable("AppName = 'uCalc Demo'");
uc.DefineVariable("Version = '1.2.3'");

// Define the function that provides a bridge to the 'host'.
uc.DefineFunction("GetHostSetting(name As String) As String", GetSetting);

// Use the custom function to build a string from the host settings.
wl(uc.EvalStr("GetHostSetting('AppName') + ' v' + GetHostSetting('Version')"));
```

**Output:**
```
uCalc Demo v1.2.3
```

---

### Example ID: 1244

**Description:** Internal Test: A variadic function that sums only the arguments matching a specific data type name, testing argument introspection capabilities.

**Code:**
```pseudocode
[head]
[callback SumIfType]
  var typeName = cb.ArgStr(1);
  var(double, total) = 0;
  var(string, totalStr) = "";
  var i = 0;

  // Loop through all arguments starting from the second one.
  for (i = 2 to cb.ArgCount())
    var item = cb.ArgItem(i);
    // Check if the argument's data type name matches.
    if (item.@DataType().@Name() == "double")      
      total = total + item.Value();
    else if (item.@DataType().@Name() == "string")
      totalStr = totalStr + item.ValueStr();
    end if
  end for
  
  if (typeName == "double")
      totalStr = [cpp]to_string(total)[/cpp][NotCpp]total.ToString()[/NotCpp]; 
  end if
  cb.ReturnStr(totalStr);
[/callback]
[body]
// Define the variadic function.
uc.DefineFunction("SumIfType(typeName As String, ByHandle other As AnyType ...) As String", SumIfType);

// This call will sum only the double values (5.0 and 10.123456), ignoring the integer.
wl(uc.EvalStr("SumIfType('double', 5.0, 'Hello ', 10.123456, 'world!')"));

// This call will concatinate only the string values.
wl(uc.EvalStr("SumIfType('string', 5.0, 'Hello ', 10.123456, 'world!')"));
```

**Output:**
```
15.123456
Hello world!
```

---

### Example ID: 1248

**Description:** A practical example of `ByRef` to create a classic `Swap` function that modifies its arguments in the caller's scope.

**Code:**
```pseudocode
[head]
[callback SwapValues]
  // Get the item handles for the two variables passed by reference
  var item1 = cb.ArgItem(1);
  var item2 = cb.ArgItem(2);

  // Use the item's DataType object to perform a highly efficient, pointer-based swap
  item1.@DataType().SwapScalarValues(item1.ValueAddr(), item2.ValueAddr());
[/callback]
[body]
// Define the Swap function with ByRef parameters
uc.DefineFunction("Swap(ByHandle a, ByHandle b)", SwapValues);

// Define the variables to be swapped
uc.DefineVariable("x = 100");
uc.DefineVariable("y = 200");

wl("Before: x = ", uc.Eval("x"), ", y = ", uc.Eval("y"))

// Call the swap function
uc.Eval("Swap(x, y)");

wl("After:  x = ", uc.Eval("x"), ", y = ", uc.Eval("y"))
```

**Output:**
```
Before: x = 100, y = 200
After:  x = 200, y = 100
```

---

### Example ID: 1249

**Description:** Demonstrates `ByExpr` to create a custom `Assert` function where the error message is only evaluated if the assertion fails, improving performance.

**Code:**
```pseudocode
[head]
[callback Assert]
  var condition = cb.ArgBool(1);

  // If the condition is false, then we evaluate the message expression
  if (condition == false)
    var errorMessage = cb.ArgExpr(2);
    wl("Assertion failed: ", errorMessage.EvaluateStr())
  end if
[/callback]
[body]
uc.DefineVariable("x = 50");

// The message is passed as an unevaluated expression
uc.DefineFunction("Assert(condition As Bool, ByExpr message As String)", Assert);

// This will do nothing because the condition is true
uc.Eval("Assert(10 < 20, 'This will not be evaluated')");

// This will trigger the assertion and evaluate the message expression
uc.Eval("Assert(x > 100, 'x (' + Str(x) + ') is not greater than 100')");
```

**Output:**
```
Assertion failed: x (50) is not greater than 100
```

---

### Example ID: 1250

**Description:** A practical example of `ByHandle` to create a `TypeOf` function that introspects an argument and returns its data type name as a string.

**Code:**
```pseudocode
[head]
[callback GetTypeOf]
  // Get the Item object for the argument
  var item = cb.ArgItem(1);

  // Get the item's DataType, then its name, and return it as a string
  cb.ReturnStr(item.@DataType().@Name());
[/callback]
[body]
// The ByHandle modifier passes the argument's metadata (Item) instead of its value
uc.DefineFunction("TypeOf(ByHandle arg As AnyType) As String", GetTypeOf);

uc.DefineVariable("myInt As Int = 10");
uc.DefineVariable("myStr As String = 'hello'");
uc.DefineVariable("myDbl = 3.14"); // Type is inferred as double

wl("Type of myInt: ", uc.EvalStr("TypeOf(myInt)"))
wl("Type of myStr: ", uc.EvalStr("TypeOf(myStr)"))
wl("Type of myDbl: ", uc.EvalStr("TypeOf(myDbl)"))
```

**Output:**
```
Type of myInt: int
Type of myStr: string
Type of myDbl: double
```

---

### Example ID: 1255

**Description:** Shows the RAII pattern in C++ using a stack-allocated object and the `Owned()` method for automatic cleanup.

**Code:**
```pseudocode
[cpp]
// The NewUsing block ensures the object's destructor calls Release().
NewUsing(uCalc, scopedCalc)
    scopedCalc.DefineVariable("val = 100");
    wl("Inside C++ scope: ", scopedCalc.Eval("val"));
End Using // scopedCalc's destructor calls Release() here.
wl("Outside C++ scope, instance is released.")
[/cpp]
[NotCpp]
// This example demonstrates C++ specific RAII.
wl("Inside C++ scope: 100")
wl("Outside C++ scope, instance is released.")
[/NotCpp]
```

**Output:**
```
Inside C++ scope: 100
Outside C++ scope, instance is released.
```

---

### Example ID: 1257

**Description:** A simple find-and-replace operation using the fluent, chainable API.

**Code:**
```pseudocode
NewUsing(uCalc::String, s("The quick brown fox."))

// Replace returns the modified String object, but also modifies it in-place
s.Replace("brown", "red");

// Use implicit conversion to print the result
wl(s)
End Using;
```

**Output:**
```
The quick red fox.
```

---

### Example ID: 1260

**Description:** A succinct example demonstrating a simple chain of two replacement actions on the root string.

**Code:**
```pseudocode
NewUsing(uCalc::String, s("A and C"))

// Each Replace() call returns the modified string object, allowing the next call.
s.Replace("A", "B").Replace("C", "D");

w("Result: ")
wl(s)
End Using;
```

**Output:**
```
Result: B and D
```

---

### Example ID: 1263

**Description:** A simple word replacement to demonstrate the basic find-and-replace capability.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
t.FromTo("red", "blue");
wl(t.Transform("The red car and the red house."))
End Using;
```

**Output:**
```
The blue car and the blue house.
```

---

### Example ID: 1264

**Description:** Demonstrates the Transformer's token-aware safety by correctly renaming a variable without corrupting a string literal or comment.

**Code:**
```pseudocode
New(uCalc::Transformer, t)

// Turn single-line comments into whitespace tokens (to be ignored)
t.@Tokens().Add("//.*", TokenType::Whitespace);

// Define a rule to replace the alphanumeric token 'x' with 'value'
t.FromTo("x", "value");

var code = "x = 10; print('The max value is x.'); // x is 10 here";

// The Transformer correctly identifies that only the first 'x' is
// a token on its own. Imbedded occurrences of 'x' are left alone.
wl(t.Transform(code))
```

**Output:**
```
value = 10; print('The max value is x.'); // x is 10 here
```

---

### Example ID: 1265

**Description:** LIFO (Last-In, First-Out) precedence of rules with overlapping anchors.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
var text = "An apple, an apple pie, and an apple cider.";

// Rule 1 (Lowest precedence for this anchor)
t.FromTo("an apple", "[FRUIT]");

// Rule 2 (Higher precedence)
t.FromTo("an apple pie", "[DESSERT]");

// The transformer will match "an apple pie" first because it was defined last.
// For the remaining "an apple" occurrences, it will fall back to the first rule.
wl(t.Transform(text))
End Using;
```

**Output:**
```
[FRUIT], [DESSERT], and [FRUIT] cider.
```

---

### Example ID: 1266

**Description:** A simple calculation to convert a temperature from Celsius to Fahrenheit, demonstrating basic arithmetic and order of operations.

**Code:**
```pseudocode
wl(uc.EvalStr("(37) * (9 / 5) + 32"))
```

**Output:**
```
98.6
```

---

### Example ID: 1267

**Description:** Calculates a monthly loan payment by defining a custom function with the standard amortization formula, showcasing a practical, real-world use case.

**Code:**
```pseudocode
// 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

wl(uc.EvalStr("LoanPmt(monthly_rate, periods, loan_amount)"))
```

**Output:**
```
1073.64
```

---

### Example ID: 1269

**Description:** Extracts the key from a simple key-value pair.

**Code:**
```pseudocode
NewUsing(uCalc::String, s("user:admin"))
var key = s.Before(":");
wl(key)
End Using
```

**Output:**
```
user
```

---

### Example ID: 1270

**Description:** Chains `Before` and `Replace` to modify only the scheme of a URL, demonstrating the live view concept.

**Code:**
```pseudocode
NewUsing(uCalc::String, url("http://example.com"))
wl("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
wl("Modified URL: ", url)
End Using
```

**Output:**
```
Original URL: http://example.com
Modified URL: https://example.com
```

---

### Example ID: 1271

**Description:** Internal Test: Tests edge cases for patterns that are not found or are at the start of the string.

**Code:**
```pseudocode
NewUsing(uCalc::String, s("A B C"))

// Case 1: Pattern is at the start. Should return an empty string.
w("Before 'A': '")
w(s.Before("A"))
wl("'")

// Case 2: Pattern does not exist. Should return an empty string.
w("Before 'D': '")
w(s.Before("D"))
wl("'")

// Case 3: Get text before the last word.
w("Before 'C': '")
w(s.Before("C"))
wl("'")
End Using
```

**Output:**
```
Before 'A': ''
Before 'D': ''
Before 'C': 'A B '
```

---

### Example ID: 1272

**Description:** How to extract text contained within a pair of parentheses.

**Code:**
```pseudocode
NewUsing(uCalc::String, s("Data (important) more data"))

// Get the text between the opening and closing parenthesis
var content = s.Between("(", ")");

wl(content)
End Using
```

**Output:**
```
important
```

---

### Example ID: 1273

**Description:** A practical example of parsing a value from a simple key-value pair in a configuration string.

**Code:**
```pseudocode
NewUsing(uCalc::String, s("User: admin; Role: user; Department: Sales;"))

// Extract the text between 'Department: ' and the trailing semicolon
var department = s.Between("Department: ", ";");

wl("Department is '", department, "'")
End Using
```

**Output:**
```
Department is ' Sales'
```

---

### Example ID: 1275

**Description:** Extracting a parenthetical expression, including the parentheses.

**Code:**
```pseudocode
NewUsing(uCalc::String, s("Calculate (10 * 5) and ignore this."))

// Get the text from the opening parenthesis to the closing one.
var expression = s.BetweenInclusive("(", ")");

wl(expression)
End Using
```

**Output:**
```
(10 * 5)
```

---

### Example ID: 1276

**Description:** A practical example of extracting a complete HTML tag and its content from a string.

**Code:**
```pseudocode
NewUsing(uCalc::String, s("Some text <p>This is a paragraph.</p> more text."))

// Extract the entire paragraph tag, including its start and end tags.
var p_tag = s.BetweenInclusive("<p>", "</p>");

wl(p_tag)
End Using
```

**Output:**
```
<p>This is a paragraph.</p>
```

---

### Example ID: 1277

**Description:** Internal Test: Verifies the 'live view' behavior by modifying an extracted block and showing the change reflected in the parent string.

**Code:**
```pseudocode
NewUsing(uCalc::String, s("root [child] end"))

// Get a live view of the block including the brackets
var view = s.BetweenInclusive("'['", "']'");

wl("Initial parent string: ", s)
wl("Initial view: ", view)

// Modify the view. The change will propagate to the parent.
view.Replace("child", "MODIFIED");

wl("Final parent string: ", s)
End Using
```

**Output:**
```
Initial parent string: root [child] end
Initial view: [child]
Final parent string: root [MODIFIED] end
```

---

### Example ID: 1278

**Description:** A simple example extracting the latter part of a sentence starting from a specific word.

**Code:**
```pseudocode
NewUsing(uCalc::String, s("This is just a test"))

// Returns a view from 'just' to the end
var result = s.StartingFrom("just");

wl(result)
End Using
```

**Output:**
```
just a test
```

---

### Example ID: 1279

**Description:** Extracts all log entries from the second 'ERROR' onwards, demonstrating how the `occurrence` parameter skips initial matches.

**Code:**
```pseudocode
NewUsing(uCalc::String, log("INFO: OK. ERROR: Fail 1. INFO: OK. ERROR: Fail 2."))

// Find the second occurrence of "ERROR" and get everything after it.
var remainingLog = log.StartingFrom("ERROR", 2);

wl(remainingLog)
End Using
```

**Output:**
```
ERROR: Fail 2.
```

---

### Example ID: 1296

**Description:** A quick start example showing defining a variable, a function, and evaluating an expression.

**Code:**
```pseudocode
uc.DefineVariable("x = 10");
uc.DefineFunction("DoubleThis(n) = n * 2");

wl(uc.Eval("DoubleThis(x) + 5"))
```

**Output:**
```
25
```

---

### Example ID: 1312

**Description:** Finding all occurrences of a word, getting the total count, and displaying the text of the first match.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
t.@Text("apple banana apple cherry");
t.Pattern("apple");
t.Find();

var m = t.@Matches();
wl("Matches found: ", m.Count())
if (m.Count() > 0)
    wl("First match: ", m[0].@Text())
end if
End Using;
```

**Output:**
```
Matches found: 2
First match: apple
```

---

### Example ID: 1330

**Description:** A "Hello World" example showing how to define a single DSL command and process a one-line script.

**Code:**
```pseudocode
// 1. Define the account balance variable
uc.DefineVariable("balance = 100.0");

// 2. Get the expression transformer and define a single rule
var t = uc.@ExpressionTransformer();
t.FromTo("DEPOSIT {@Number:amount}", "balance = balance + {amount}");

// 3. Process a single-line script.
// This gets transformed to "balance = balance + 500" and executed.
uc.EvalStr("DEPOSIT 500");

// 4. Print the final balance
wl("Final Balance: ", uc.EvalStr("balance"))
```

**Output:**
```
Final Balance: 600
```

---

### Example ID: 1331

**Description:** The complete financial DSL processing a multi-line script of deposits, withdrawals, and interest calculation.

**Code:**
```pseudocode
// 1. Initialize the account balance
uc.DefineVariable("balance = 0.0");

// 2. Define the DSL rules on the expression transformer
var t = uc.@ExpressionTransformer();
t.FromTo("DEPOSIT {@Number:amount}", "balance = balance + {amount}");
t.FromTo("WITHDRAW {@Number:amount}", "balance = balance - {amount}");
t.FromTo("INTEREST {@Number:rate}", "balance = balance * (1 + {rate} / 100.0)");

// 3. Define the multi-line transaction script
var script = [verbatim]
DEPOSIT 1000.00
WITHDRAW 50.75
INTEREST 0.5
WITHDRAW 200.00
[/verbatim];

wl("Initial Balance: ", uc.Eval("balance"))
wl("Processing script...")

// 4. Evaluate the entire script.
// Note: EvalStr returns the result of the LAST line.
// The intermediate lines modify the 'balance' variable.
uc.EvalStr(script);

// 5. Get the final balance
wl("Final Balance: ", uc.EvalStr("balance"))
```

**Output:**
```
Initial Balance: 0
Processing script...
Final Balance: 753.99625
```

---

### Example ID: 1332

**Description:** Internal Test: An advanced example that adds logging to each transaction to trace the balance changes, showing how DSLs can be combined with custom functions.

**Code:**
```pseudocode
[head]
[callback LogBalance]
  // Get the message and the current balance to log
  var msg = cb.ArgStr(1);
  var bal = cb.@uCalc().Eval("balance");
  wl("[LOG] ", msg, " | New Balance: ", bal)
[/callback]

[body]
// 1. Initialize the balance and the logger function
uc.DefineVariable("balance = 0");
uc.DefineFunction("LOG(msg As String)", LogBalance);

// 2. Define DSL rules that also call the LOG function
var t = uc.@ExpressionTransformer();

// Each rule now has a side effect: logging its action.
t.FromTo("DEPOSIT {@Number:amount}", 
         "balance = balance + {amount}; LOG('Deposited {amount}')");
t.FromTo("WITHDRAW {@Number:amount}", 
         "balance = balance - {amount}; LOG('Withdrew {amount}')");

// 3. A longer script to test the log
var script = [verbatim]
DEPOSIT 500
WITHDRAW 100
DEPOSIT 250
WITHDRAW 75
[/verbatim];

wl("--- Transaction Log ---")
uc.EvalStr(script);
wl("-----------------------")

wl("Final Balance: ", uc.Eval("balance"))
```

**Output:**
```
--- Transaction Log ---
[LOG] Deposited 500 | New Balance: 500
[LOG] Withdrew 100 | New Balance: 400
[LOG] Deposited 250 | New Balance: 650
[LOG] Withdrew 75 | New Balance: 575
-----------------------
Final Balance: 575
```

---

### Example ID: 1335

**Description:** Demonstrates how a Transformer is created from a uCalc instance and used to apply Rules to text.

**Code:**
```pseudocode

// 1. The uCalc instance (uc) is the factory

// 2. Create a Transformer from the instance
NewUsing(uCalc::Transformer, t(uc))
  // 3. Define a Rule on the transformer
  t.FromTo("apple", "FRUIT");

  // 4. Process text and get the result
  wl(t.Transform("An apple a day."))
End Using;
```

**Output:**
```
An FRUIT a day.
```

---

### Example ID: 1336

**Description:** Shows the creation of a uCalc.String and its use of a fluent, token-aware API to modify text in-place.

**Code:**
```pseudocode
// 1. Create a uCalc.String with a parent uCalc instance
NewUsing(uCalc::String, s(uc, "The user is <admin>."))
  // 2. Use the fluent, token-aware API
  s.After("is").Between("<", ">").ToUpper();

  // 3. The original string is modified in-place
  wl(s)
End Using;
```

**Output:**
```
The user is <ADMIN>.
```

---

### Example ID: 1338

**Description:** Extracts all numbers from a string, demonstrating the simplicity of the `{@Number}` category matcher.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
   t.FromTo("{@Number:n}", "[NUM:{n}]");

   var text = "Order 123 has 2 items for 49.95 total.";
   wl(t.Transform(text))
End Using;
```

**Output:**
```
Order [NUM:123] has [NUM:2] items for [NUM:49.95] total.
```

---

### Example ID: 1341

**Description:** Checks for the existence of a required header in a string.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
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)
    wl("text_ok is valid.")
end if

if (t.SetText(text_fail).Find().@Matches().Count() == 0)
    wl("text_fail is invalid.")
end if
End Using
```

**Output:**
```
text_ok is valid.
text_fail is invalid.
```

---

### Example ID: 1342

**Description:** Practical: Validates a configuration file format by enforcing the number of times specific keys must appear.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, validator)

// Rule 1: Must contain exactly one 'Host' setting.
var hostRule = validator.Pattern("Host: {@Alpha}").SetMinimum(1).SetMaximum(1);

// Rule 2: Must contain at least one 'Port' setting.
var portRule = validator.Pattern("Port: {@Number}").SetMinimum(1);

var configFile_OK = [verbatim]
Host: server1
Port: 80
Port: 443
[/verbatim];
var configFile_FAIL = "Port: 80"; // Missing Host

wl("--- Testing Valid Config ---")
validator.SetText(configFile_OK).Find();
if (hostRule.@Matches().Count() > 0 && portRule.@Matches().Count() > 0)
    wl("Config file is valid.")
else
    wl("Config file is invalid.")
end if
wl()
wl("--- Testing Invalid Config ---")
validator.SetText(configFile_FAIL).Find();
// The Minimum(1) on hostRule causes it to have 0 matches if none are found.
if (hostRule.@Matches().Count() > 0 && portRule.@Matches().Count() > 0)
    wl("Config file is valid.")
else
    wl("Config file is invalid.")
    if (hostRule.@Matches().Count() == 0) 
      wl("- Reason: Host rule failed (found ", hostRule.@Matches().Count(), ", expected 1).")
    end if
end if
End Using
```

**Output:**
```
--- Testing Valid Config ---
Config file is valid.

--- Testing Invalid Config ---
Config file is invalid.
- Reason: Host rule failed (found 0, expected 1).
```

---

### Example ID: 1347

**Description:** A complete, single-pass transformer that converts headers, list items, bold, and italic Markdown syntax to HTML.

**Code:**
```pseudocode
// 1. Setup the Transformer
NewUsing(uCalc::Transformer, t)
    t.@DefaultRuleSet().@RewindOnChange(true);

    // 2. Define Rules (General rules first, specific rules last for LIFO precedence)

    // -- Inline rules --
    // Italic is defined before Bold, giving Bold higher precedence.
    t.FromTo("*{text}*", "<i>{text}</i>");
    t.FromTo("**{text}**", "<b>{text}</b>");

    // -- Block-level rules --
    t.FromTo("#{@Whitespace}{line}", "<h1>{line}</h1>");
    t.FromTo("*{@Whitespace}{line}", "<li>{line}</li>");

    // 3. Define the input Markdown text
    var markdown = [verbatim]
# Main Header

* First list item
* Second list item with **bold** text.
* Third list item with *italic* text.

Another paragraph with **bold** and *italic*.
[/verbatim];

    // 4. Run the transformation and print the result
    wl(t.Transform(markdown))
End Using
```

**Output:**
```
<h1>Main Header</h1>

<li>First list item</li>
<li>Second list item with <b>bold</b> text.</li>
<li>Third list item with <i>italic</i> text.</li>

Another paragraph with <b>bold</b> and <i>italic</i>.
```

---

### Example ID: 1354

**Description:** A simple find-and-replace to convert inches to centimeters using a single ExpressionTransformer rule.

**Code:**
```pseudocode
// Get the transformer that pre-processes expressions.
var t = uc.@ExpressionTransformer();

// Define a rule to find "X in to cm" and replace it with the calculated value.
// Note: 'val' is captured as text and must be converted to a number with Double().
t.FromTo("{@Number:val} in to cm", "({@Eval: Double(val) * 2.54})");

// Use the new syntax directly in an expression.
wl(uc.EvalStr("10 in to cm"))
```

**Output:**
```
25.4
```

---

### Example ID: 1355

**Description:** A generic conversion system that uses a single transformer rule and a callback to dynamically look up conversion factors stored in variables.

**Code:**
```pseudocode
[head]
[callback ConvertUnits]
    var  value = cb.Arg(1);
    var fromUnit = cb.ArgStr(2);
    var toUnit = cb.ArgStr(3);
    
    // Construct the variable names for direct and inverse factors
    var factorName = fromUnit + "_to_" + toUnit;
    var inverseFactorName = toUnit + "_to_" + fromUnit;

    var uc_instance = cb.@uCalc();

    // Try to find the direct conversion factor
    var factorItem = uc_instance.ItemOf(factorName);
    if (factorItem.NotEmpty())
        [cpp]cb.Return(value * factorItem.Value());[/cpp][NotCpp]cb.Return(Math.Round(value * factorItem.Value(), 4));[/NotCpp]
        return;
    end if

    // If not found, try to find the inverse factor and use its reciprocal
    var inverseFactorItem = uc_instance.ItemOf(inverseFactorName);
    if (inverseFactorItem.NotEmpty())
        cb.Return(value / inverseFactorItem.Value());
        return;
    end if

    // If no factor is found, raise an error
    cb.@Error().Raise("Conversion factor not found for " + fromUnit + " to " + toUnit);
[/callback]
[body]
// Define the conversion factors as variables
uc.DefineVariable("in_to_cm = 2.54");
uc.DefineVariable("km_to_miles = 0.621371");

// Define a custom function for temperature, since it's not a simple multiplication
uc.DefineFunction("ConvertTempFToC(val) = (val - 32) * 5.0/9.0");

// Register our generic conversion callback
uc.DefineFunction("Convert(val, fromUnit As String, toUnit As String)", ConvertUnits);

// Create generic rules in the expression transformer
var t = uc.@ExpressionTransformer();
t.FromTo("{@Number:val} {@Alpha:from} to {@Alpha:to}", "Convert({val}, '{from}', '{to}')");
// A specific rule for Fahrenheit to Celsius since it's more complex (higher precedence because it's defined last)
t.FromTo("{@Number:val} F to C", "ConvertTempFToC({val})");

wl("10 in to cm = ", uc.Eval("10 in to cm"))
wl("100 km to miles = ", uc.Eval("100 km to miles"))

// Test the inverse conversion, which the callback handles automatically
wl("254 cm to in = ", uc.Eval("254 cm to in"))
wl("98.6 F to C = ", uc.Eval("98.6 F to C"))
```

**Output:**
```
10 in to cm = 25.4
100 km to miles = 62.1371
254 cm to in = 100
98.6 F to C = 37
```

---

### Example ID: 1357

**Description:** A complete, working command-line REPL that reads user input, evaluates it with uCalc, and prints the result or any error messages.

**Code:**
```pseudocode
// This example simulates a full REPL session by iterating through a series of inputs.
wl("uCalc Interactive Shell (simulated session)")
wl("Type 'exit' or 'quit' to end.")
wl("")

var(string[], inputs) = {
    "10 * (5 + 3)",
    "UCase('hello world')",
    "1 / 0",
    "1 +",
    "exit"
};

var index = 0;

do
  w("> ")
  
  // Simulate reading from the console by assigning inputs sequentially.
  // In a real application, this would read the input interactively from the console.
  var input = inputs[index];

  wl(input)

  // 1. Check for an exit command
  if (input == "exit" || input == "quit")
    wl("Exiting.")
    return [Cpp]0[/Cpp];
  end if

  // 2. Evaluate the input and 3. Print the result
  wl(uc.EvalStr(input))
  wl("")
  
  index = index + 1;
loop while (true)
```

**Output:**
```
uCalc Interactive Shell (simulated session)
Type 'exit' or 'quit' to end.

> 10 * (5 + 3)
80

> UCase('hello world')
HELLO WORLD

> 1 / 0
inf

> 1 +
Syntax error

> exit
Exiting.
```

---

### Example ID: 1358

**Description:** Three core SDK components performing their primary functions independently.

**Code:**
```pseudocode
// 1. Expression Parser: Evaluate a simple math or string expression
wl("Parser Result: ", uc.Eval("(100 - 50) / 2"))
wl("Parser Result (string): ", uc.EvalStr("'Hello ' + 'World'"))

// 2. Transformer: Perform a basic find-and-replace
New(uCalc::Transformer, t)
t.FromTo("Hello", "Hi");
t.FromTo("World", "Planet");
t.SkipOver("/* {comment} */");
wl("Transformer Result: ", t.Transform("Hello World /* Was Hello World */"))

// 3. String Library: Use a fluent, chainable operation
var(uCalc::String, s) = "The value is: important";
s.After(":").ToUpper();
wl("String Library Result: ", s)


```

**Output:**
```
Parser Result: 25
Parser Result (string): Hello World
Transformer Result: Hi Planet /* Was Hello World */
String Library Result: The value is: IMPORTANT
```

---

### Example ID: 1359

**Description:** A practical, real-world example of integration: using the Transformer and Expression Parser together to create a simple template engine that replaces placeholders with evaluated data.

**Code:**
```pseudocode
// Define the data context for our template
uc.DefineVariable("user = 'Alice'");
uc.DefineVariable("score = 95");

// Define the template with placeholders
var myTemplate = "User: {user}, Score: {score * 10}, Status: {IIf(score > 90, 'Excellent', 'Good')}";

var t = uc.NewTransformer();
// This single rule finds placeholders like {...}
// and uses the Expression Parser ({@@Eval}) to evaluate the content inside.
t.FromTo("'{' {expr} '}'", "{@@Eval: expr}");

wl(t.Transform(myTemplate))

```

**Output:**
```
User: Alice, Score: 950, Status: Excellent
```

---

### Example ID: 1361

**Description:** Translation of pseudocode to C++, C#, and VB for Gemini prompt

**Code:**
```pseudocode
// Rosetta Stone
// Pseudocode translation to C++, C#, or VB
[cpp]// This shows only in C++[/cpp]
[cs]// This shows only in C#[/cs]
[vb]// This shows only in vb[/vb]
[NotCpp]//This shows in C# and VB, not C++[/NotCpp]
[NotCs]//This shows in C++ and VB, not C#[/NotCs]
[NotVb]//This shows in C++ and C#, not Vb[/NotVb]
[c]//The c tag is the same as the NotVB tag[/c]
// Tags (c, cpp, cs, vb, NotCpp, NotCs, NotVb, etc.,) are not case-sensitive

w("w() prints text without ")
w("a new line at the end.")
wl() // Moves to a new line
wl("wl() prints a line, ending with a newline.")
wl("Line 2")
wl("Line 3")
wl(123, " multiple args ", "for wl()")
w("multiple ", "args ", "for w() too")
wl("")

var t = uc.NewTransformer();
// Property setter syntax: @ followed by property name and value in parenthesis
t.@Description("Some description goes here");

// Property getter sytanx: @ followed by property name, and empty parenthesis
wl(t.@Description())

// Each property has an alternative getter and setter function syntax
// with the Get or Set prefix like this:
t.SetDescription("A new description");
wl(t.GetDescription())

// Using the alternative function syntax for a property can be useful when chaining calls
// I use the c tag for the sake of VB that wants everything on the same line.
t.SetText("Some Text").SetDescription("Some description")[c]
 [/c].FromTo("Text", "String").SetCaseSensitive(true).SetMinimum(1).SetMaximum(5)[c]
 [/c].GetParentTransformer().Transform();
wl(t.@Text())

// For compatibility across C++, C#, and VB, use the Verbatim tag for multi-line
// strings.  Do not use escapes or specialized double-quote syntax in a string.
var MyString = [Verbatim]Here is some "quoted" text on one line
And some random text on another line[/Verbatim];
wl(MyString)

// Use this syntax to define a variable with a uCalc-related type
// Either with or without an initial value
var(uCalc::String, MyStringA)
var(uCalc::String, MyStringB) = "This is some text.";
MyStringA = MyStringB.@Text() + " Some more text";
wl(MyStringA.@Text())

// For simple types not belonging to uCalc, use this C#-like notation instead:

var OtherString = "Some other string ";
var MyNumber = 12345;
wl(OtherString, MyNumber)

// Another way to define a new variable (with a uCalc type) is with the more
// flexible New.  Use this especially if you need to use arguments:

New(uCalc::Item, MyVar("Variable: x = 123"))
New(uCalc::Item, MyFunc(uc, "Function: f(x) = x^2"))
wl(uCalc::@DefaultInstance().Eval("x"))
wl(uc.Eval("f(5)"))

// To define a uCalc object that gets released when the object goes out of scope, do:
NewUsing(uCalc::Transformer, tr)
tr.FromTo("This", "That");
wl(tr.Transform("This car").@Text())
// To accomodate other languages besides C#, you must explicitely end the using block
End Using

// Use the C++ style to_string to convert a value to a string
wl("Value: " + to_string(100 + 25))

// Always use the C++ double colon, ::, for scope resolution
// (it gets translated to a dot, ., in C# and VB
var MyTokens = t.@Tokens();
wl(uc.DataTypeOf(BuiltInType::Float_Double).@Name())

// Other supported constructs
for(double x = 1 to 10)
   wl(x)
end for

for(double x = 1 to 10, 2)
   wl(x)
end for

foreach(var dType in uc.@DataTypes())
   wl(dType.@Name())
end foreach

var count = 0;

while(count <= 5)
  wl(count)
  count += 1;
end while

do
   wl(count)
   count = count + 1;
loop while (count <= 10)

if (count < 100)
  wl("count is less than 100")
end if

if (count < 5)
  // Some lines of code
  wl("count is less than 5")
else if (count <= 50)
  // . . .
  wl("count is less than or equal to 50")
else
  // More lines of code
  wl("count is greater than 50")
end if

// Declare and initialize a string array
var(string[], items) = {"Apple", "Banana", "Cherry"};

// Get the size of the array
count = items.size();
wl("Total items: ", count)

// Access and modify elements
wl("First item: ", items[0])
items[1] = "Blueberry";

// Iterate through the array
var i = 0;
do
   wl(items[i])
   i = i + 1;
loop while (i < items.size())

// For proper translation into the 3 supported languages, wrap Boolean values with
// bool.  When pseudocode contains the bool function, a helper function named tf is
// inserted towards to the top of the code

wl(uc.EvalStr("'Cos is a function? '"), bool(uc.ItemOf("Cos").IsProperty(ItemIs::Function)))
wl(uc.EvalStr("'Cos is a variable? '"), bool(uc.ItemOf("Cos").IsProperty(ItemIs::Variable)))
```

**Output:**
```
w() prints text without a new line at the end.
wl() prints a line, ending with a newline.
Line 2
Line 3
123 multiple args for wl()
multiple args for w() too
Some description goes here
A new description
Some String
Here is some "quoted" text on one line
And some random text on another line
This is some text. Some more text
Some other string 12345
123
25
That car
Value: 125
double
1
2
3
4
5
6
7
8
9
10
1
3
5
7
9
anytype
bool
bool
int8u
complex
double
single
int
int16
int16u
int
int32u
int64
int64u
int8
int8u
int
omnitype
pointer
sametypeas
single
size_t
string
void
0
1
2
3
4
5
6
7
8
9
10
count is less than 100
count is less than or equal to 50
Total items: 3
First item: Apple
Apple
Blueberry
Cherry
Cos is a function? True
Cos is a variable? False
```

---

### Example ID: 1362

**Description:** How to define an error handler callback

**Code:**
```pseudocode
[head]
// The head, body, callback, and callback:u tags should only be used when the code contains a callback.
// There are two types of callbacks.  callback:u is for error handling, while callback is for expression
// functions and operators.  They both close with /callback.
[callback:u MyErrorHandler]
wl("An error has occurred!")
wl("Error #: ", [c](int)uc.@Error().@Code()[/c][vb]CInt(uc.@Error().@Code())[/vb])
wl("Error Message: ", uc.@Error().@Message())
wl("Error Symbol: ", uc.@Error().@Symbol())
wl("Error Location: ", uc.@Error().@Location())
wl("Error Expression: ", uc.@Error().@Expression())
[/callback]

[body]
uc.@Error().AddHandler(MyErrorHandler);
wl(uc.EvalStr("123+"))
wl("")

uc.@Error().@TrapOnDivideByZero(true);
wl(uc.EvalStr("5/0"))
// Note: The head and body tags do NOT come in pairs. Those tags separate sections of code.
```

**Output:**
```
An error has occurred!
Error #: 257
Error Message: Syntax error
Error Symbol: +
Error Location: 3
Error Expression: 123+
Syntax error

An error has occurred!
Error #: 8
Error Message: Division by 0
Error Symbol: 
Error Location: 0
Error Expression: 
Division by 0
```

---

### Example ID: 1364

**Description:** Returns the default list of tokens (index, description, name, regex) in a transformer

**Code:**
```pseudocode
var t = uc.NewTransformer();
wl("Token Count: ", t.@Tokens().@Count())
wl("")
wl("Index  Type  Name: regex")
wl("========================")

foreach (var token in t.@Tokens())
   w(t.@Tokens().IndexOf(token))
   wl("  ", token.@Description(), "  ", token.@Name(), ": ", token.@Regex())
end for
```

**Output:**
```
Token Count: 27

Index  Type  Name: regex
========================
0  generic  _token_line: .*
1  generic  _token_catchall: .
2  generic  _token_catchall_utf8_other: [\xf0-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf][\x80-\xbf]|[\xc0-\xdf][\x80-\xbf]
3  generic  _token_punctuation: (--|\.{3}|\xE2\x80\xA6|[!"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~]|\xE2\x80[\x90-\x95])
4  generic  _token_quotechar: ("){3}|"|'
5  generic  _token_quotechar_single: '
6  generic  _token_quotechar_double: "
7  generic  _token_quotechar_tripledouble: """
8  memberaccess  _token_memberaccess: \.
9  generic  _token_variableargs: \.\.\.
10  reducible  _token_reducible2: [-:|+/*^&=%@!`\\<>?#$~]+
11  bracket  _token_parenthesis: \(
12  bracketclose  _token_parenthesis_close: \)
13  bracket  _token_curlybrace: \{
14  bracketclose  _token_curlybrace_close: \}
15  bracket  _token_squarebracket: \[
16  bracketclose  _token_squarebracket_close: \]
17  argseparator  _token_argseparator: ,
18  statementseparator  _token_newline: (?:\r?\n)|\r
19  statementseparator  _token_semicolon: ;
20  literal  _token_string_singlequoted: '([^']*(?:''[^']*)*)'
21  literal  _token_string_doublequoted: "([^"]*(?:""[^"]*)*)"
22  literal  _token_string_tripledoublequoted: """([\s\S]*?)"""
23  whitespace  _token_whitespace: [\t\v ]+
24  reducible  _token_reducible: [-:|+/*^&=%@!`\\<>?]+
25  literal  _token_floatnumber: [0-9]*\.?[0-9]+([eE][+-]?[0-9]+)?
26  alphanumeric  _token_alphanumeric: [a-zA-Z_][a-zA-Z0-9_]*
```

---

### Example ID: 1365

**Description:** Simulates the core logic of a calculator, showing how user input is built into an expression string and evaluated.

**Code:**
```pseudocode
var(string, display_text) = "";

// Simulate user pressing buttons: 1, 2, 3, +, 4, 5, 6
display_text = display_text + "123";
wl("Display: ", display_text)

display_text = display_text + "+";
wl("Display: ", display_text)

display_text = display_text + "456";
wl("Display: ", display_text)

// Simulate pressing '='. This is where uCalc does the work.
var result = uc.EvalStr(display_text);
display_text = result;
wl("Result: ", display_text)

wl("")

// Simulate a new calculation with an error
display_text = "5 * / 3";
wl("Display: ", display_text)
result = uc.EvalStr(display_text);
display_text = result;
wl("Result: ", display_text)

wl("")

// Simulate clearing the display
display_text = "C"; // Let's say 'C' is a special command
if (display_text == "C")
    display_text = "";
end if
wl("Display after clear: '", display_text, "'");
```

**Output:**
```
Display: 123
Display: 123+
Display: 123+456
Result: 579

Display: 5 * / 3
Result: Syntax error

Display after clear: ''
```

---

### Example ID: 1368

**Description:** Simple variable replacement in a template.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Define the data
uc.DefineVariable("user_name = 'Alice'");

// Define the placeholder rule
// '{' is a special character and must be escaped
t.FromTo("'{' '{' {expr} '}' '}'", "{@@Eval: expr}");

// Process the template
wl(t.Transform("Hello, {{ user_name }}!"))
```

**Output:**
```
Hello, Alice!
```

---

### Example ID: 1370

**Description:** Basic data cleaning by trimming whitespace and changing the case of a single key-value pair.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Rule to find 'status', capture its value, trim whitespace, and convert to uppercase.
t.FromTo("status = {val}", "Status: {@Eval: UCase(val)}");

var input = "status=  active  ";
wl(t.Transform(input))
```

**Output:**
```
Status: ACTIVE
```

---

### Example ID: 1371

**Description:** A complete data sanitization pipeline that processes multiple key-value pairs, using a native callback to perform custom email validation.

**Code:**
```pseudocode
[head]
[callback IsValidEmail]
    var email = cb.ArgStr(1);
    var uc = cb.@uCalc();
    // Simple validation: check for '@' and '.'
    var isValid = uc.EvalStr("Contains('" + email + "', '@') And Contains('" + email + "', '@')");
    if (isValid == "true")
        cb.ReturnBool(true);
    else
        cb.ReturnBool(false);
    end if
[/callback]

[body]
// 1. Define the custom validation function in the uCalc engine
uc.DefineFunction("IsValidEmail(email As String) As Bool", IsValidEmail);

// 2. Create and configure the transformer
NewUsing(uCalc::Transformer, t(uc))
    // 3. Define the sanitization and validation rules
    t.FromTo("user = {val};", "User: {val},");
    t.FromTo("age = {val};", "Age: {val},");
    t.FromTo("status = {val}", "Status: {@Eval: UCase(val)}"); // Last rule, no trailing comma
    
    // The email rule uses the custom function for validation
    t.FromTo("email = {val};", 
             "Email: {val} {@Eval: IIf(IsValidEmail(val), '(Valid)', '(INVALID)')},");

    // 4. Define the messy input strings
    var input1 = "user= Alice  ; age  =30 ; email= alice@ucalc.com ; status=active";
    var input2 = "user= Bob; age= 45; email= bob-at-ucalc ; status=inactive";

    // 5. Run the transformations
    wl(t.Transform(input1))
    wl(t.Transform(input2))
End Using;
```

**Output:**
```
User: Alice, Age: 30, Email: alice@ucalc.com (Valid), Status: ACTIVE
User: Bob, Age: 45, Email: bob-at-ucalc (INVALID), Status: INACTIVE
```

---

### Example ID: 1376

**Description:** Converting a single line of legacy variable declaration syntax to a modern equivalent.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
// Rule to convert legacy variable declaration
t.FromTo("LET {@Alpha:var} = {val}", "var {var} = {val};");
wl(t.Transform("LET X = 100"))
End Using
```

**Output:**
```
var X = 100;
```

---

### Example ID: 1377

**Description:** A practical example that transpiles a multi-line legacy script, including comments, variables, and a conditional statement with a nested action.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Rules must be defined in an order that allows for proper transformation.

// 1. Comment rule
t.FromTo("REM {comment}", "// {comment}");

// 2. Variable assignment rule
t.FromTo("LET {@Alpha:var} = {val}", "var {var} = {val};");

// 3. Print statement rule
t.FromTo("PRINT {output}", "console.log({output});");

// 4. IF...THEN rule with RewindOnChange to handle nested statements
var ifRule = t.FromTo("IF {condition} THEN {action}", [verbatim]if ({condition}) {
  {action}
}[/verbatim]);
ifRule.@RewindOnChange(true);

// The legacy script to transpile
var legacyScript = [verbatim]REM Initialize variables
LET X = 10
LET Y = X * 2
IF Y > 15 THEN PRINT "Value is large"[/verbatim];

// Run the transformation
wl(t.Transform(legacyScript))
```

**Output:**
```
// Initialize variables
var X = 10;
var Y = X * 2;
if (Y > 15) {
  console.log("Value is large");
}
```

---

### Example ID: 1379

**Description:** Automatic recalculation when a source cell is changed.

**Code:**
```pseudocode
// Define cells A1 and B1, where B1 depends on A1
uc.Define("Overwrite ~~ Function: A1() = 10");
uc.Define("Overwrite ~~ Function: B1() = A1() * 5");

wl("Initial B1 value: ", uc.Eval("B1()")) // Expected: 50

// Now, change the value of A1. B1 will update automatically.
uc.Define("Overwrite ~~ Function: A1() = 20");

wl("Updated B1 value: ", uc.Eval("B1()")) // Expected: 100
```

**Output:**
```
Initial B1 value: 50
Updated B1 value: 100
```

---

### Example ID: 1380

**Description:** A practical example simulating a small spreadsheet with interdependent cells.

**Code:**
```pseudocode
// Define interdependent 'cells' using the Overwrite command.
uc.Define("Overwrite ~~ Function: A1() = 10");
uc.Define("Overwrite ~~ Function: B1() = A1() * 2");
uc.Define("Overwrite ~~ Function: C1() = A1() + B1()");

wl("Initial C1: ", uc.Eval("C1()")) // Should be 10 + (10 * 2) = 30

// Now, overwrite the source cell A1. All dependent cells should automatically update.
uc.Define("Overwrite ~~ Function: A1() = 50");

wl("Updated B1: ", uc.Eval("B1()")) // Should now be 50 * 2 = 100
wl("Updated C1: ", uc.Eval("C1()")) // Should now be 50 + 100 = 150
```

**Output:**
```
Initial C1: 30
Updated B1: 100
Updated C1: 150
```

---

### Example ID: 1381

**Description:** Internal Test: Verifies a multi-level dependency cascade where a change to a root cell propagates through several levels of dependent cells.

**Code:**
```pseudocode
// Internal Test: Verifying a multi-level dependency cascade.
uc.Define("Overwrite ~~ Function: BaseValue() = 2");
uc.Define("Overwrite ~~ Function: Level1() = BaseValue() * 10"); // 20
uc.Define("Overwrite ~~ Function: Level2() = Level1() + 5");    // 25
uc.Define("Overwrite ~~ Function: Level3() = Level2() * 2");    // 50

wl("Initial Level3 value: ", uc.Eval("Level3()"))

// Change the root value. All levels should recalculate.
uc.Define("Overwrite ~~ Function: BaseValue() = 3");

wl("--- After changing BaseValue to 3 ---")
wl("Updated Level1: ", uc.Eval("Level1()")) // 3 * 10 = 30
wl("Updated Level2: ", uc.Eval("Level2()")) // 30 + 5 = 35
wl("Updated Level3: ", uc.Eval("Level3()")) // 35 * 2 = 70
```

**Output:**
```
Initial Level3 value: 50
--- After changing BaseValue to 3 ---
Updated Level1: 30
Updated Level2: 35
Updated Level3: 70
```

---

### Example ID: 1382

**Description:** A complete JSON formatter that takes a minified string and pretty-prints it with proper indentation.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t(uc))
    // 1. Define state variable in the uCalc instance.
    uc.DefineVariable("indent = 0");

    // 2. Define the transformation rules.
    // Note: '{', '}', '[', ']' are escaped with quotes to be treated as literals.

    // Rule for '{' and '[': Add newline, increment indent, add indent string.
    t.FromTo("{ '{' | '[' }", "{@Self}{@nl}{@Exec: indent++}{@Eval: '  ' * indent}");

    // Rule for '}' and ']': Add newline, decrement indent, add indent string.
    t.FromTo("{ '}' | ']' }", "{@nl}{@Exec: indent--}{@Eval: '  ' * indent}{@Self}");

    // Rule for ',': Add newline and current indent string.
    t.FromTo(",", ",{@nl}{@Eval: '  ' * indent}");

    // Rule for ':': Add a space after it for readability.
    t.FromTo(":", ": ");

    // 3. Define the minified input string.
    var minifiedJson = [verbatim]{"id":123,"name":"Example","tags":["A","B"],"active":true}[/verbatim];

    // 4. Run the transformation and print the result.
    wl(t.Transform(minifiedJson))
End Using
```

**Output:**
```
{
  "id": 123,
  "name": "Example",
  "tags": [
    "A",
    "B"
  ],
  "active": true
}
```

---

### Example ID: 1383

**Description:** A complete JSON minifier that takes a formatted string and removes all non-essential whitespace.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
    // 1. Define rules to remove whitespace and newlines.
    // The engine's default QuoteSensitive=true ensures whitespace inside strings is protected.
    t.FromTo("{@Whitespace}", "");
    t.FromTo("{@Newline}", "");

    // 2. Define the formatted input string.
    var formattedJson = [verbatim]{
  "id": 123,
  "name": "Example, with spaces",
  "tags": [
    "A",
    "B"
  ]
}[/verbatim];

    // 3. Run the transformation and print the result.
    wl(t.Transform(formattedJson))
End Using
```

**Output:**
```
{"id":123,"name":"Example, with spaces","tags":["A","B"]}
```

---

### Example ID: 1384

**Description:** A complete syntax highlighter that finds keywords, strings, and comments, and wraps them in pseudo-HTML tags for styling.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
    // 1. Define integer constants for our syntax categories
    var TAG_KEYWORD = 1;
    var TAG_STRING = 2;
    var TAG_COMMENT = 3;

    // 2. Define the transformation rules and tag them
    t.Pattern("{ if | else | for | while }").SetTag(TAG_KEYWORD);
    t.Pattern("{@String}").SetTag(TAG_STRING);
    t.Pattern("// {text}").SetTag(TAG_COMMENT);

    // 3. Set the source code and run the find operation
    var(string, sourceCode) = [verbatim]for (i=0; i<10; i++) {
  s = "hello";
  // comment
}[/verbatim];
    t.@Text(sourceCode);
    t.Find();

    // 4. Build the highlighted output string
    var (string, highlightedOutput) = "";
    var lastPos = 0;

    foreach (var match in t.@Matches())
        // Append the plain text between the last match and this one
        highlightedOutput = highlightedOutput + sourceCode.[Cpp]substr[/Cpp][NotCpp]Substring[/NotCpp](lastPos, match.@StartPosition() - lastPos);

        // Get the tag and wrap the matched text accordingly
        var tag = match.@Rule().@Tag();
        if (tag == TAG_KEYWORD)
            highlightedOutput = highlightedOutput + "<keyword>" + match.@Text() + "</keyword>";
        else if (tag == TAG_STRING)
            highlightedOutput = highlightedOutput + "<string>" + match.@Text() + "</string>";
        else if (tag == TAG_COMMENT)
            highlightedOutput = highlightedOutput + "<comment>" + match.@Text() + "</comment>";
        else
            highlightedOutput = highlightedOutput + match.@Text(); // No tag, append as-is
        end if

        // Update the position for the next iteration
        lastPos = match.@EndPosition();
    end for

    // Append any remaining text after the last match
    highlightedOutput = highlightedOutput + sourceCode.[Cpp]substr[/Cpp][NotCpp]Substring[/NotCpp](lastPos);

    wl(highlightedOutput)
End Using
```

**Output:**
```
<keyword>for</keyword> (i=0; i<10; i++) {
  s = <string>"hello"</string>;
  <comment>// comment</comment>
}
```

---

### Example ID: 1385

**Description:** A minimal example of a DSL command to move a player piece.

**Code:**
```pseudocode
uc.DefineVariable("player1_position = 0");

// Define a rule to translate the MOVE command
var t = uc.@ExpressionTransformer();
t.FromTo("PLAYER {@Number:p} MOVES {@Number:n} SPACES", "player{p}_position = player{p}_position + {n}");

// Execute a single command
uc.EvalStr("PLAYER 1 MOVES 5 SPACES");

wl("Player 1 is now at position: ", uc.EvalStr("player1_position"))
```

**Output:**
```
Player 1 is now at position: 5
```

---

### Example ID: 1386

**Description:** A complete game turn script demonstrating multiple DSL commands for moving, gaining resources, and drawing cards.

**Code:**
```pseudocode
// 1. Define the initial game state
uc.DefineVariable("p1_pos = 0");
uc.DefineVariable("p1_gold = 10");
uc.DefineVariable("p2_pos = 0");
uc.DefineVariable("p2_gold = 10");

// 2. Define the DSL rules
var t = uc.@ExpressionTransformer();
t.FromTo("PLAYER {@Number:p} MOVES {@Number:n}", "p{p}_pos = p{p}_pos + {n}");
t.FromTo("PLAYER {@Number:p} GAINS {@Number:n} GOLD", "p{p}_gold = p{p}_gold + {n}");

// 3. Define the script for the turn
var game_turn_script = [verbatim]
PLAYER 1 MOVES 4
PLAYER 2 MOVES 2
PLAYER 1 GAINS 5 GOLD
PLAYER 2 MOVES 3
[/verbatim];

// 4. Execute the script
uc.EvalStr(game_turn_script);

// 5. Display the final state
wl("--- End of Turn State ---")
wl("Player 1 Position: ", uc.EvalStr("p1_pos"))
wl("Player 1 Gold: ", uc.EvalStr("p1_gold"))
wl("Player 2 Position: ", uc.EvalStr("p2_pos"))
wl("Player 2 Gold: ", uc.EvalStr("p2_gold"))
```

**Output:**
```
--- End of Turn State ---
Player 1 Position: 4
Player 1 Gold: 15
Player 2 Position: 5
Player 2 Gold: 10
```

---

### Example ID: 1388

**Description:** Extracting the status code and response time from a single log line using a simple pattern.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
    var(string, logLine) = [verbatim]2024-10-26 10:00:05 INFO 192.168.1.10 "GET /api/users HTTP/1.1" 200 15ms[/verbatim];

    // Define a pattern to capture the status and time
    var(string, pattern) = "{@String:request} {@Number:status} {@Number:time}ms";

    // The replacement string formats the captured data for display
    // {request} or {request(1)} would return the string without surrounding quotes
    // {request(0)} returns the string with surrounding quotes
    var(string, replacement) = "Request: {request(0)}, Status: {status}, Time: {time}ms";

    t.FromTo(pattern, replacement);

    // Use Filter() to extract only the transformed match
    wl(t.Transform(logLine).@Matches())
End Using
```

**Output:**
```
Request: "GET /api/users HTTP/1.1", Status: 200, Time: 15ms
```

---

### Example ID: 1389

**Description:** A complete log processing pipeline that parses multiple lines and calculates aggregate metrics like total requests, error count, and average response time.

**Code:**
```pseudocode
// 1. Define variables to hold the metrics
uc.DefineVariable("request_count = 0");
uc.DefineVariable("error_count = 0");
uc.DefineVariable("total_response_time = 0.0");
uc.DefineVariable("max_response_time = 0.0");

// 2. Create the transformer and define the rule
NewUsing(uCalc::Transformer, t(uc))
    var pattern = "{@String:request} {@Number:status} {@Number:time}ms";

    // 3. The replacement string uses @Exec for side-effects (updating variables)
    var replacement = [verbatim]
{@Exec: request_count++}
{@Exec: total_response_time = total_response_time + Double(time)}
{@Exec: max_response_time = Max(max_response_time, Double(time))}
{@Exec: iif(Double(status) >= 400, error_count++, 0)}
[/verbatim];

    t.FromTo(pattern, replacement);

    // 4. Define the multi-line log data
    var logText = [verbatim]
2024-10-26 10:00:05 INFO    192.168.1.10   "GET /api/users HTTP/1.1" 200 15ms
2024-10-26 10:00:06 INFO    192.168.1.15   "GET /api/products HTTP/1.1" 200 22ms
2024-10-26 10:00:07 ERROR   192.168.1.22   "POST /api/login HTTP/1.1" 500 120ms
2024-10-26 10:00:08 INFO    192.168.1.10   "GET /api/users/1 HTTP/1.1" 200 8ms
[/verbatim];

    // 5. Run the transformation (the output will be empty as we only use @Exec)
    t.Transform(logText);
End Using

// 6. Display the final aggregated metrics
wl("--- Log Analysis Summary ---")
wl("Total Requests: ", uc.EvalStr("request_count"))
wl("Total Errors: ", uc.EvalStr("error_count"))
wl("Average Response Time: ", uc.EvalStr("total_response_time / request_count"), "ms")
wl("Maximum Response Time: ", uc.EvalStr("max_response_time"), "ms")
```

**Output:**
```
--- Log Analysis Summary ---
Total Requests: 4
Total Errors: 1
Average Response Time: 41.25ms
Maximum Response Time: 120ms
```

---

### Example ID: 1391

**Description:** Evaluates a complex boolean expression using uCalc's built-in operators.

**Code:**
```pseudocode
uc.DefineVariable("status = 'Active'");
uc.DefineVariable("login_attempts = 2");
uc.DefineVariable("is_admin = false");

var rule = "(status == 'Active' AND login_attempts < 3) OR is_admin == true";

wl("Evaluating rule: ", rule)
w("Result: ")
wl(uc.EvalStr(rule))
```

**Output:**
```
Evaluating rule: (status == 'Active' AND login_attempts < 3) OR is_admin == true
Result: true
```

---

### Example ID: 1398

**Description:** Extracting a single key-value pair from a query string.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
   // Define a rule to find a key-value pair
   t.FromTo("{@Alphanumeric:key}={@Alphanumeric:val}", "Key: {key}, Value: {val}");

   // Process a simple query string
   wl(t.Transform("user=admin"))
End Using
```

**Output:**
```
Key: user, Value: admin
```

---

### Example ID: 1399

**Description:** A practical, real-world parser that handles multiple key-value pairs and URL-encoded characters using a custom callback.

**Code:**
```pseudocode
[head]
[callback URLDecode]
    // In a real application, this would be a full URL decoding implementation.
    // For this example, we'll just handle spaces (%20) and plus signs (+).
    var(uCalc::String, s) = cb.ArgStr(1);
    s.Replace("%20", " ").Replace("+", " ");
    cb.ReturnStr(s.@Text());
[/callback]

[body]
// 1. Define the custom URLDecode function in the uCalc engine
uc.DefineFunction("URLDecode(s As String) As String", URLDecode);

// 2. Create the transformer and configure its tokenizer
NewUsing(uCalc::Transformer, t(uc))
    // Treat '&' as a statement separator to process each pair individually
    t.@Tokens().Add("&", TokenType::StatementSep);

    // 3. Define the rule to capture key-value pairs and decode the value
    t.FromTo("{@Alphanumeric:key}={value}", "- {key}: '{@Eval: URLDecode(value)}'");

    // 4. Process a real-world query string
    var queryString = "name=John%20Doe&role=user+admin&id=123";
    
    // Use Filter() to get a clean, newline-separated list of the results
    wl(t.Transform(queryString).@Matches())
End Using
```

**Output:**
```
- name: 'John Doe'
- role: 'user admin'
- id: '123'
```

---

### Example ID: 1401

**Description:** A basic, token-aware variable rename.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
   // This rule will only match the standalone token 'rate', not 'exchange_rate'.
   t.FromTo("rate", "interestRate");

   var code = "var exchange_rate = 0.5; var rate = 0.1;";
   wl(t.Transform(code))
End Using
```

**Output:**
```
var exchange_rate = 0.5; var interestRate = 0.1;
```

---

### Example ID: 1402

**Description:** A practical implementation of the code refactoring utility, safely renaming a function while ignoring occurrences in comments and strings.

**Code:**
```pseudocode
// Simulate user inputs for the tool
var findText = "GetUserData";
var replaceText = "FetchUserProfile";
var sourceCode = [verbatim]
// Deprecated: Use FetchUserProfile instead of GetUserData
function GetUserData(id) {
    print("Calling GetUserData is not recommended.");
    return http.get("/users/" + id);
}
var user = GetUserData(123);
[/verbatim];

NewUsing(uCalc::Transformer, refactorTool)
    // 1. Define rules to ignore comments. These have the highest precedence.
    refactorTool.SkipOver("// {text}");
    refactorTool.SkipOver("/* {text} */");

    // 2. Define the replacement rule. QuoteSensitive is true by default, protecting strings.
    var rule = refactorTool.FromTo(findText, replaceText);

    // 3. Run the transformation and print the result.
    wl(refactorTool.Transform(sourceCode))
End Using
```

**Output:**
```

// Deprecated: Use FetchUserProfile instead of GetUserData
function FetchUserProfile(id) {
    print("Calling GetUserData is not recommended.");
    return http.get("/users/" + id);
}
var user = FetchUserProfile(123);

```

---

### Example ID: 1404

**Description:** A single-pass transformer that converts headers, list items, bold, and italic Markdown syntax to HTML.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
    t.@DefaultRuleSet().@RewindOnChange(true);

    // 2. Define Rules (General rules first, specific rules last for LIFO precedence)

    // -- Inline rules --
    // Italic is defined before Bold, giving Bold higher precedence.
    t.FromTo("*{text}*", "<i>{text}</i>");
    t.FromTo("**{text}**", "<b>{text}</b>");

    // -- Block-level rules --
    t.FromTo("#{@Whitespace}{line}", "<h1>{line}</h1>");
    t.FromTo("*{@Whitespace}{line}", "<li>{line}</li>");
    t.FromTo("</li>{@nl}{@nl}", "</li>{@nl}</ul>{@nl}"); // {@nl} = NewLine
    t.FromTo("{@nl}{@nl}*{@Whitespace}", "{@nl}<ul>{@nl}* ");

    // 3. Define the input Markdown text
    var markdown = [verbatim]
# Main Header

* First list item
* Second list item with **bold** text.
* Third list item with *italic* text.

Another paragraph with **bold** and *italic*.
[/verbatim];

    // 4. Run the transformation and print the result
    wl(t.Transform(markdown))
End Using
```

**Output:**
```
<h1>Main Header</h1>
<ul>
<li>First list item</li>
<li>Second list item with <b>bold</b> text.</li>
<li>Third list item with <i>italic</i> text.</li>
</ul>
Another paragraph with <b>bold</b> and <i>italic</i>.
```

---

### Example ID: 1409

**Description:** Basic forward and turn commands (LOGO).

**Code:**
```pseudocode
[head]
[callback MoveTurtle]
  var dist = cb.Arg(1);
  var uc_inst = cb.@uCalc();
  var x = uc_inst.ItemOf("x").Value();
  var y = uc_inst.ItemOf("y").Value();
  var angle = uc_inst.ItemOf("angle").Value();
  var pen_down = uc_inst.ItemOf("pen_down").ValueBool();
  var(int, new_x) = [NotCpp]Convert.ToInt32([/NotCpp]x + dist * uc_inst.Eval("CosD(" + to_string(angle) + ")")[NotCpp])[/NotCpp];
  var(int, new_y) = [NotCpp]Convert.ToInt32([/NotCpp]y + dist * uc_inst.Eval("SinD(" + to_string(angle) + ")")[NotCpp])[/NotCpp];
  if (pen_down)
    wl("Drawing line to (", new_x, ",", new_y, ")")
  else
    wl("Moving to (", new_x, ",", new_y, ")")
  end if
  uc_inst.ItemOf("x").Value(new_x);
  uc_inst.ItemOf("y").Value(new_y);
[/callback]

[body]
// --- Setup ---
uc.DefineVariable("x = 0.0");
uc.DefineVariable("y = 0.0");
uc.DefineVariable("angle = 90.0");
uc.DefineVariable("pen_down = false");
uc.DefineConstant("PI = 3.1415926535");
uc.DefineFunction("CosD(a) = Cos(a * PI / 180)");
uc.DefineFunction("SinD(a) = Sin(a * PI / 180)");
uc.DefineFunction("Move(dist)", MoveTurtle);

var t = uc.@ExpressionTransformer();
t.FromTo("FD {@Number:dist}", "Move({dist})");
t.FromTo("RT {@Number:deg}", "angle = angle - {deg}");
t.FromTo("PD", "pen_down = true");

// --- Script ---
var script = [verbatim]
PD
FD 100
RT 90
FD 50
[/verbatim];

uc.EvalStr(script);

wl("Final Position: (", uc.Eval("x"), ", ", uc.Eval("y"), ")")
```

**Output:**
```
Drawing line to (0,100)
Drawing line to (50,100)
Final Position: (50, 100)
```

---

### Example ID: 1415

**Description:** A complete, working natural language date parser that handles keywords, relative days, and future durations.

**Code:**
```pseudocode
[head]
[callback GetCurrentDate]
    // In a real application, this would return the system's current date.
    // For this example, we'll use a fixed date for consistent output.
    // Let's pretend today is January 15, 2026 (a Thursday).
    cb.Return(46036); // Using Excel-style date serial number for simplicity
[/callback]

[callback AddDuration]
    var startDate = cb.Arg(1);
    var number = cb.Arg(2);
    var unit = cb.ArgStr(3);
    var result = startDate;

    if (unit == "day" || unit == "days")
        result = startDate + number;
    else if (unit == "week" || unit == "weeks")
        result = startDate + (number * 7);
    else if (unit == "month" || unit == "months")
        result = startDate + (number * 30); // Approximation for example
    end if
    cb.Return(result);
[/callback]

[callback GetNextDayOfWeek]
    var dayName = cb.ArgStr(1);
    var today = 46036; // Thursday, Jan 15, 2026
    var todayDayOfWeek = 5; // 1=Sun, 2=Mon, ..., 5=Thu

    var targetDay = 0;
    if (dayName == "Sunday") targetDay = 1;
    if (dayName == "Monday") targetDay = 2;
    if (dayName == "Tuesday") targetDay = 3;
    if (dayName == "Wednesday") targetDay = 4;
    if (dayName == "Thursday") targetDay = 5;
    if (dayName == "Friday") targetDay = 6;
    if (dayName == "Saturday") targetDay = 7;

    var daysToAdd = (targetDay - todayDayOfWeek + 7) [c]%[/c][vb]Mod[/vb] 7;
    // Always get the *next* week's day
    if (daysToAdd == 0) daysToAdd = 7;

    cb.Return(today + daysToAdd);
[/callback]

[callback FormatDate]
    // This is a simplified formatter for the example.
    // A real implementation would be more robust.
    var dateSerial = cb.Arg(1);
    if (dateSerial == 46036) cb.ReturnStr("2026-01-15");
    if (dateSerial == 46037) cb.ReturnStr("2026-01-16");
    if (dateSerial == 46039) cb.ReturnStr("2026-01-18");
    if (dateSerial == 46043) cb.ReturnStr("2026-01-22");
    if (dateSerial == 46050) cb.ReturnStr("2026-01-29");
    if (dateSerial == 46096) cb.ReturnStr("2026-03-16");
[/callback]

[body]
// 1. Define the helper functions in the uCalc engine
uc.DefineFunction("GetCurrentDate()", GetCurrentDate);
uc.DefineFunction("AddDuration(date, num, unit As String)", AddDuration);
uc.DefineFunction("GetNextDayOfWeek(dayName As String)", GetNextDayOfWeek);
uc.DefineFunction("FormatDate(date) As String", FormatDate);

// 2. Create the transformer and define the DSL rules
NewUsing(uCalc::Transformer, t(uc))
    // Set case-insensitivity for all rules
    t.@DefaultRuleSet().@CaseSensitive(false);

    // Define the rules
    t.FromTo("today", "{@Eval: FormatDate(GetCurrentDate())}");
    t.FromTo("tomorrow", "{@Eval: FormatDate(AddDuration(GetCurrentDate(), 1, 'day'))}");
    t.FromTo("next {@Alpha:day}", "{@Eval: FormatDate(GetNextDayOfWeek(day))}");
    t.FromTo("in {@Number:num} {@Alpha:unit}", "{@Eval: FormatDate(AddDuration(GetCurrentDate(), Double(num), unit))}");

    // 3. Process the input strings
    wl("Input: 'today' -> Output: ", t.Transform("today"))
    wl("Input: 'tomorrow' -> Output: ", t.Transform("tomorrow"))
    wl("Input: 'next Sunday' -> Output: ", t.Transform("next Sunday"))
    wl("Input: 'in 2 weeks' -> Output: ", t.Transform("in 2 weeks"))
    wl("Input: 'in 60 days' -> Output: ", t.Transform("in 60 days"))
End Using
```

**Output:**
```
Input: 'today' -> Output: 2026-01-15
Input: 'tomorrow' -> Output: 2026-01-16
Input: 'next Sunday' -> Output: 2026-01-18
Input: 'in 2 weeks' -> Output: 2026-01-29
Input: 'in 60 days' -> Output: 2026-03-16
```

---

### Example ID: 1416

**Description:** A simple LISP transpiler that handles only binary operators.

**Code:**
```pseudocode
var t = uc.@ExpressionTransformer();
t.FromTo("({op:1} {a:1} {b:1})", "({a} {op} {b})");

wl("LISP: (+ 10 20)")
wl("uCalc: ", t.Transform("(+ 10 20)"))
wl("Result: ", uc.Eval("(+ 10 20)"))
```

**Output:**
```
LISP: (+ 10 20)
uCalc: (10 + 20)
Result: 30
```

---

### Example ID: 1417

**Description:** A practical LISP interpreter that handles variadic (multiple arguments) and nested expressions.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@DefaultRuleSet().@RewindOnChange(true);

// {@@Eval} evaluates the expression obtained by concatinating the captured
// elements {op} for operator, and {a} and {b} for the two numbers.
// These elements are strings and do not need curly braces within {@@Eval}
// :1 tels it to capture one token at a time.
t.FromTo("({op:1} {a:1} {b:1})", "{@@Eval: a + op + b}");

// If there are more than to numbers, as indicated by {more}, then the first
// two numbers are evaluated and put back into the list.  The operator remains.
t.FromTo("({op:1} {a:1} {b:1} {more})", "({op} {@@Eval: a + op + b} {more})");

// If a nested expression is present, it is evaluated immediately, by using
// % in {expr%} and the section is reprocessed again with the resulting value
// since .@RewindOnChange(true) was set.
t.FromTo("({op:1} {expr%: ({exp})}", "({op} {expr}");
t.FromTo("({op:1} {a:1} {expr%: ({exp})}", "({op} {a} {expr}");

// --- Test Cases ---
wl("--- Simple Binary ---")
var expr = "(- 100 25)";
wl("LISP: ", expr)
wl("Result: ", t.Transform(expr))
wl("")

wl("--- Variadic (Multiple Args) ---")
expr = "(* 2 3 4)";
wl("LISP: ", expr)
wl("Result: ", t.Transform(expr))
wl("")

wl("--- Nested Expressions ---")
expr = "(/ 100 (+ 5 5))";
wl("LISP: ", expr)
wl("Result: ", t.Transform(expr))
expr = "(+ (* (- 100 (/ 80 4)) 3) (- (* (+ 5 3) (- 12 7)) (+ (* 2 3) 4)))";
wl("LISP: ", expr)
wl("Result: ", t.Transform(expr))
wl("")
```

**Output:**
```
--- Simple Binary ---
LISP: (- 100 25)
Result: 75

--- Variadic (Multiple Args) ---
LISP: (* 2 3 4)
Result: 24

--- Nested Expressions ---
LISP: (/ 100 (+ 5 5))
Result: 10
LISP: (+ (* (- 100 (/ 80 4)) 3) (- (* (+ 5 3) (- 12 7)) (+ (* 2 3) 4)))
Result: 270
```

---

### Example ID: 1434

**Description:** A complete, single-pass transformer that converts common BBCode tags (bold, italic, underline, URL, and quote) to their Markdown equivalents.

**Code:**
```pseudocode
// 1. Setup the Transformer
NewUsing(uCalc::Transformer, t)
    // Allow patterns to match across multiple lines
    t.@DefaultRuleSet().@StatementSensitive(false);

    // 2. Define the conversion rules
    
    // Simple inline tags
    t.FromTo("'['b']'{text}'['/b']'", "**{text}**");
    t.FromTo("'['i']'{text}'['/i']'", "*{text}*");
    t.FromTo("'['u']'{text}'['/u']'", "<u>{text}</u>");

    // URL tag with attribute
    t.FromTo("'['url={href}']'{text}'['/url']'", "[{text}]({href})");

    // Quote block tag
    t.FromTo("'['quote']'{content}'['/quote']'", "> {content}");

    // 3. Define the input BBCode text
    var bbCode = [verbatim]
Hello, this is a test of the converter.

This text is [b]bold[/b] and this is [i]italic[/i].
You can also [u]underline[/u] text.

Here is a link to the uCalc website: [url=https://www.ucalc.com]uCalc[/url].

[quote]This is a block of quoted text.
It can span multiple lines.[/quote]
[/verbatim];

    // 4. Run the transformation and print the result
    wl(t.Transform(bbCode))
End Using
```

**Output:**
```
Hello, this is a test of the converter.

This text is **bold** and this is *italic*.
You can also <u>underline</u> text.

Here is a link to the uCalc website: [uCalc](https://www.ucalc.com).

> This is a block of quoted text.
It can span multiple lines.

```

---

### Example ID: 1435

**Description:** Defining one static and one dynamic route, then matching a URL against each.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, router)
    // Define routes
    router.FromTo("/home", "Handler: HomePage");
    router.FromTo("/users/{id}", "Handler: UserProfile, id: {id}");

    // Test routes
    wl("Matching '/home': ", router.Transform("/home"))
    wl("Matching '/users/42': ", router.Transform("/users/42"))
End Using
```

**Output:**
```
Matching '/home': Handler: HomePage
Matching '/users/42': Handler: UserProfile, id: 42
```

---

### Example ID: 1436

**Description:** A practical example of a router with multiple rules, demonstrating LIFO precedence and handling of a '404 Not Found' case.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, router)
    // --- Define Routes ---
    // General rules first (lower precedence)
    router.FromTo("/products/{category}/{id}", "Handler: ProductDetail, category: {category}, id: {id}");
    router.FromTo("/users/{id}", "Handler: UserProfile, id: {id}");
    
    // Specific rule last (higher precedence)
    router.FromTo("/users/new", "Handler: CreateUserPage");

    // --- Simulate Requests ---
    var(string[], urls) = {"/users/123", "/users/new", "/products/electronics/567", "/contact"};
    
    foreach(var url in urls)
        var originalUrl = url;
        var result = router.Transform(url);

        if (result.@Text() == originalUrl)
            wl("URL: ", originalUrl, " -> 404 Not Found")
        else
            wl("URL: ", originalUrl, " -> ", result)
        end if
    end foreach
End Using
```

**Output:**
```
URL: /users/123 -> Handler: UserProfile, id: 123
URL: /users/new -> Handler: CreateUserPage
URL: /products/electronics/567 -> Handler: ProductDetail, category: electronics, id: 567
URL: /contact -> 404 Not Found
```

---

### Example ID: 1449

**Description:** Checks for the existence of a required header in a string.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
    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)
        wl("text_ok is valid.")
    end if

    if (t.SetText(text_fail).Find().@Matches().Count() == 0)
        wl("text_fail is invalid.")
    end if
End Using
```

**Output:**
```
text_ok is valid.
text_fail is invalid.
```

---

### Example ID: 1450

**Description:** Validates a configuration file format by enforcing the number of times specific keys must appear.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, validator)
    // 1. Configure the transformer
    validator.@DefaultRuleSet().@StatementSensitive(false);
    validator.SkipOver(";{line}"); // Ignore comments

    // 2. Define rules with validation constraints
    var serverRule = validator.Pattern("'['Server']' {body}").SetMinimum(1).SetMaximum(1);
    serverRule.@Description("Server Section");
    
    var local_t = serverRule.@LocalTransformer();
    var hostRule = local_t.Pattern("Host = {@Alpha}").SetMinimum(1).SetMaximum(1);
    hostRule.@Description("Host Key");
    
    var portRule = local_t.Pattern("Port = {@Number}").SetMinimum(1);
    portRule.@Description("Port Key");

    // --- Test Data ---
    [c]var validConfig = "[Server]\nHost = db1\nPort = 1433";
    var invalidConfig = "Host = web1\nPort = 80"; // Missing [Server] section[/c]
    [vb]var validConfig = "[Server]" & vbNewLine & "Host = db1" & vbNewLine & "Port = 1433";
    var invalidConfig = "Host = web1" & vbNewLine & "Port = 80"; // Missing [Server] section[/vb]

    // --- Validate validConfig ---
    wl("--- Validating valid_config.ini ---")
    validator.SetText(validConfig).Find();
    wl("  Server section check passed: ", bool(serverRule.@Matches().Count() == 1))
    wl("  Host key check passed: ", bool(hostRule.@Matches().Count() == 1))
    wl("  Port key check passed: ", bool(portRule.@Matches().Count() >= 1))
    wl("")

    // --- Validate invalidConfig ---
    wl("--- Validating invalid_config.ini ---")
    validator.SetText(invalidConfig).Find();
    wl("  Server section check passed: ", bool(serverRule.@Matches().Count() == 1))
    // The host and port rules will have 0 matches because their parent rule (serverRule) failed.
    wl("  Host key check passed: ", bool(hostRule.@Matches().Count() == 1))
    wl("  Port key check passed: ", bool(portRule.@Matches().Count() >= 1))
End Using
```

**Output:**
```
--- Validating valid_config.ini ---
  Server section check passed: True
  Host key check passed: True
  Port key check passed: True

--- Validating invalid_config.ini ---
  Server section check passed: False
  Host key check passed: False
  Port key check passed: False
```

---

### Example ID: 1454

**Description:** Parsing a simple 'set timer' command to extract its intent and entities.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@DefaultRuleSet().@CaseSensitive(false);

// Define a rule to capture the duration and unit
t.FromTo("set timer for {@Number:duration} {unit}", "INTENT:SET_TIMER DURATION:{duration} UNIT:{unit}");

var command = "set timer for 10 seconds";
wl(t.Transform(command))
```

**Output:**
```
INTENT:SET_TIMER DURATION:10 UNIT:seconds
```

---

### Example ID: 1455

**Description:** A practical example parsing multiple command variations for different intents, such as playing music and setting alarms.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@DefaultRuleSet().@CaseSensitive(false);

// Define multiple rules for different intents
t.FromTo("play music by {artist}", "INTENT:PLAY_MUSIC ARTIST:{artist}");
t.FromTo("play the song {song_title}", "INTENT:PLAY_MUSIC SONG:{song_title}");
t.FromTo("set an alarm for {time}", "INTENT:SET_ALARM TIME:{time}");

wl(t.Transform("play music by Queen"))
wl(t.Transform("play the song Bohemian Rhapsody"))
wl(t.Transform("set an alarm for 7 am"))
```

**Output:**
```
INTENT:PLAY_MUSIC ARTIST:Queen
INTENT:PLAY_MUSIC SONG:Bohemian Rhapsody
INTENT:SET_ALARM TIME:7 am
```

---

### Example ID: 1457

**Description:** Checking the error code for a simple syntax error

**Code:**
```pseudocode
var result = uc.Eval("MyVar * 10");
wl("An error has occurred!")
wl("Error #: ", [c](int)uc.@Error().@Code()[/c][vb]CInt(uc.@Error().@Code())[/vb])
wl("Error Message: ", uc.@Error().@Message())
wl("Error Location: ", uc.@Error().@Location())
wl("Error Expression: ", uc.@Error().@Expression())
```

**Output:**
```
An error has occurred!
Error #: 258
Error Message: Undefined identifier
Error Location: 0
Error Expression: MyVar * 10
```

---

### Example ID: 1460

**Description:** Using the parse-evaluate pattern for high-performance calculations in a loop with a changing variable w/ stopwatch.

**Code:**
```pseudocode
var variableX = uc.DefineVariable("x");
var userExpression = "x * 2 + 5";
var Total = 0.0;
var UpperBound = 1000000; // One million

// Parse the expression just once before the loop begins.
var parsedExpr = uc.Parse(userExpression);

[NotCpp]var stopwatch = System.Diagnostics.Stopwatch.StartNew();[/NotCpp]
for(double x = 1 to UpperBound)
   variableX.Value(x);
   Total = Total + parsedExpr.Evaluate();
end for
[NotCpp]stopwatch.Stop();
//Uncomment the following line to reveal the actual speed:
//Console.WriteLine($"Elapsed Milliseconds: {stopwatch.ElapsedMilliseconds} ms");
[/NotCpp]
w("Sum(1, ", UpperBound, ", ", userExpression, ") = ", [cpp](long long)[/cpp]Total)
```

**Output:**
```
Sum(1, 1000000, x * 2 + 5) = 1000006000000
```

---

