DWScript supports an expression-based if syntax, often called the ternary operator in other languages. It allows you to select a value based on a condition within a single expression.
The full syntax is if condition then expression1 else expression2.
var count := 10;
var status := if count > 0 then 'Active' else 'Empty';
PrintLn(status); Active
Unlike the if statement, the ternary if is an expression that returns a value. Both branches must return compatible types.
If the else clause is omitted, the expression evaluates to the default value for the result type if the condition is false.
| Type | Default Value |
|---|---|
| Integer / Float | 0 |
| Boolean | False |
| String | '' (Empty string) |
| Object / Class | nil |
| Variant | Unassigned |
var score := -5;
// If score is not positive, returns 0 (default for Integer)
var positiveScore := if score > 0 then score;
PrintLn(positiveScore); 0
The ternary operator can infer types and even works with class types for polymorphic results.
type TBase = class end;
type TChild = class(TBase) end;
var cond := True;
// Result is TBase, even though one branch is TChild
var obj := if cond then TBase.Create else TChild.Create;
PrintLn(obj.ClassName); TBase
Ternary expressions can be nested to handle multiple conditions.
var val := 2;
var description := if val = 1 then 'One'
else if val = 2 then 'Two'
else 'Many';
PrintLn(description); Two
Pass conditional values directly to functions without temporary variables.
procedure Log(msg: String);
begin
PrintLn('LOG: ' + msg);
end;
var priority := True;
Log(if priority then 'URGENT' else 'Normal'); LOG: URGENT
The ternary operator can return arrays or sets. Note that for arrays, you often need an explicit type to assist inference.
var selection: array of String := if True then ['A', 'B'] else ['C'];
PrintLn(selection.Length); 2