How can I execute in Delphi a conditional statements in a String?
In PHP there is something like this:
<?php
echo "Hello (isset($name) ? $name : 'Guest'));
?>
I'm assuming you actually want to evaluate code that is not known until runtime. That's the only reason why you would have code in a string. If my assumption is correct, then you cannot do that readily in Delphi. Delphi is compiled. So in order to execute Delphi code you need to compile it.
You could consider using a scripting language for this part of your program. There are many available.
Of course, if all you want is a conditional operator in Delphi then there is none built in but the RTL provides IfThen:
function IfThen(AValue: Boolean; const ATrue: string;
AFalse: string = ''): string;
Description
Conditionally returns one of two specified values.
IfThen checks the expression passed as AValue and returns ATrue if it evaluates to true, or AFalse if it evaluates to false. In Delphi, if the AFalse parameter is omitted, IfThen returns 0 or an empty string when AValue evaluates to False.
the closest thing you can get in Delphi is this :
Writeln('Hello ' + IIf(Name='', 'Guest', Name));
where IIf is defined as:
function iif(Test: boolean; TrueRes, FalseRes: string): string;
begin
if Test then
Result := TrueRes
else
Result := FalseRes;
end;
Please mind that this example only works with strings...
EDIT
As David suggested you can also use the IfThen function from the StrUtils unit
For a type independent IIF, use this:
function IIF(pResult: Boolean; pIfTrue: Variant; pIfFalse: Variant): Variant;
begin
if pResult then
Result := pIfTrue
else
Result := pIfFalse;
end;
Related
if x <> '' then begin
Result := True;
end else
begin
Result := False;
end;
For when the if statement will be executed?
Basic constructs like this behave in Pascal Script the same as in Pascal.
Free Pascal documentation for If..then..else statement says:
The expression between the if and then keywords must have a Boolean result type. If the expression evaluates to True then the statement following the then keyword is executed.
If the expression evaluates to False, then the statement following the else keyword is executed, if it is present.
The expression x <> '' means: the (string) variable x not equals an empty string.
So overall, the code does: If x is not an empty string, set Result to True, else set Result to False. Note that Result is a special identifier used to set a return value of a function in which it is used.
Actually, the code can be simplified to a single statement:
Result := (x <> '');
(brackets are for readability only, they are not required)
At the moment I'm converting a project written in VBA to Delphi and have stumbled upon a problem with converting some Subs with Optional arguments.
Say, there is a Sub declaration (just an example, actual Subs have up to 10 optional parameters):
Sub SetMark
(x0 As Double, y0 As Double,
Optional TextOffset As Integer =5,
Optional TextBefore As String = "",
Optional Text As String = "",
Optional TextAfter As String = "mm",
Optional Color As String = "FFFFFF",
Optional ArrowPresent As Boolean = True)
That Sub subsequently can be called like this:
Call SetMark (15, 100,,,"135")
Call SetMark (100, 100, 8,, "My text here..", "")
'a lot of calls here
The Optional arguments are very flexible here, you can omit any of them, and you can assign a value to any of them as well. Unlike in Delphi.
Procedure SetMark
(x0: real; y0: real,
TextOffset: Integer =5;
TextBefore: ShortString = '';
Text: ShortString = '';
TextAfter: ShortString = 'mm';
Color: ShortString = 'FFFFFF';
ArrowPresent: Boolean = True);
It seems you cannot just make a copy of VBA call:
SetMark (15, 100,,,'135');// error here
So, the question is: is there any way to convert that Subs to Delphi procedures keeping the same flexibility in parameters?
My first idea was to use default parameters, but it doesn't work.
As for now it seems in Delphi I will have to pass all the parameters in the list with their values directly but that means a lot of work for reviewing and proper porting of VBA calls.
Any ideas?
Is there any way to convert the VBA subroutines to Delphi procedures, still keeping the same flexibility in parameters?
There is no way to achieve that – that flexibility to omit parameters, other than at the end of the list, simply does not exist.
For methods of automation objects, you can use named parameters, as described here: Named/optional parameters in Delphi? However, I very much recommend that you don't implement your classes as automation objects just to get that functionality.
Whenever you switch between languages, you will find differences that are inconvenient. That is inevitable. The best approach is to try to find the best way to solve the problem in the new language, rather than trying to force idioms from the old language into the new language.
In this case you might want to use overloaded functions or parameter objects as ways to alleviate this inconvenience.
Just to expand on the idea of refactoring to use a parameter object, you could declare a record like:
TSetMarkParams = record
x0 : double;
y0 : double;
TextOffset : integer;
TextBefore : string;
Text : string;
TextAfter : string;
Color : string;
ArrowPresent : boolean;
constructor Create(Ax0, Ay0 : double);
end;
And implement the constructor to populate default values as :
constructor TSetMarkParams.Create(Ax0, Ay0 : double);
begin
x0 := Ax0;
y0 := Ay0;
TextOffset := 5;
TextBefore := '';
Text := '';
TextAfter := 'mm';
Color := 'FFFFFF';
AllowPresent := true;
end;
Your procedure would then have signature :
procedure SetMark(ASetMarkParams : TSetMarkParams);
Which you could then, using your example of SetMark (15, 100,,,'135'); call as :
var
LSetMarkParams : TSetMarkParams
begin
LSetMarkParams := TSetMarkParams.Create(15, 100);
LSetMarkParams.Text := '135';
SetMark(LSetMarkParams);
end;
As collateral benefit, the above is much more readable as it saves you from going blind trying to count commas when returning to debug a troublesome method call.
Why does this code:
w: word;
s: String;
begin
str(w, s);
generate this warning in XE7:
[dcc32 Warning] Unit1.pas(76): W1057 Implicit string cast from 'ShortString' to 'string'
Tom
System.Str is an intrinsic function that dates from a byegone era. The documentation says this:
procedure Str(const X [: Width [:Decimals]]; var S: String);
....
Notes: However, on using this procedure, the compiler may issue a warning: W1057 Implicit string cast from '%s' to '%s' (Delphi).
If a string with a predefined minimum length is not needed, try using the IntToStr function instead.
Since this is an intrinsic, there is likely something extra going on. Behind the scenes, the intrinsic function is implemented by a call to an RTL support function that yields a ShortString. Compiler magic then turns that into a string. And warns you of the implicit conversion. The compiler magic transforms
Str(w, s);
into
s := _Str0Long(w);
Where _Str0Long is:
function _Str0Long(val: Longint): _ShortStr;
begin
Result := _StrLong(val, 0);
end;
Since _Str0Long returns a ShortString then the compiler has to generate code to perform the implicit converstion from ShortString to string when it assigns to your variable s. And of course it's then natural that you see W1057.
The bottom line is that Str only exists to retain compatibility with legacy Pascal ShortString code. New code should not be calling Str. You should do what the documentation says and call IntToStr:
s := IntToStr(w);
Or perhaps:
s := w.ToString;
More Pascal woes.
Say I have 2 Units, MainUnit, and ExampleClass.
MainUnit:
Unit MainUnit;
interface
Uses ExampleClass;
function ReturnFive: Integer;
implementation
function ReturnFive: Integer;
begin
ReturnFive := 5;
end;
begin
end.
ExampleClass:
Unit ExampleClass;
{$mode objfpc}
interface
type
ClassThing = Class
SampleValue: Integer;
end;
implementation
begin
end.
Now, I'd like to only import MainUnit, but still be able to use ClassThing. MainUnit uses ExampleClass, but ClassThing isn't usable when you import MainUnit.
I don't really want to just use ExampleClass along with MainUnit, I'd prefer to keep it in one uses statement.
How do you do this?
put
type ClassThing = ExampleCLass.ClassThing;
in the interface of mainunit.
The principle also works for consts, but only "real" ones (not typed ones which are more initialized vars):
const myconst = unitname.myconst;
Nearly all my much used types are similar aliases, so that I can easily move around where they are defined without changing the uses clause in all the businesscode units
I am trying to compare two strings in Smalltalk, but I seem to be doing something wrong.
I keep getting this error:
Unhandled Exception: Non-boolean receiver. Proceed for truth.
stringOne := 'hello'.
stringTwo := 'hello'.
myNumber := 10.
[stringOne = stringTwo ] ifTrue:[
myNumber := 20].
Any idea what I'm doing wrong?
Try
stringOne = stringTwo
ifTrue: [myNumber := 20]`
I don't think you need square brackets in the first line
Found great explanation. Whole thing is here
In Smalltalk, booleans (ie, True or False) are objects: specifically, they're instantiations of the abstract base class Boolean, or rather of its two subclasses True and False. So every boolean has type True or False, and no actual member data. Bool has two virtual functions, ifTrue: and ifFalse:, which take as their argument a block of code. Both True and False override these functions; True's version of ifTrue: calls the code it's passed, and False's version does nothing (and vice-versa for ifFalse:). Here's an example:
a < b
ifTrue: [^'a is less than b']
ifFalse: [^'a is greater than or equal to b']
Those things in square brackets are essentially anonymous functions, by the way. Except they're objects, because everything is an object in Smalltalk. Now, what's happening there is that we call a's "<" method, with argument b; this returns a boolean. We call its ifTrue: and ifFalse: methods, passing as arguments the code we want executed in either case. The effect is the same as that of the Ruby code
if a < b then
puts "a is less than b"
else
puts "a is greater than or equal to b"
end
As others have said, it will work the way you want if you get rid of the first set of square brackets.
But to explain the problem you were running into better:
[stringOne = stringTwo ] ifTrue:[myNumber := 20]
is passing the message ifTrue: to a block, and blocks do not understand that method, only boolean objects do.
If you first evaluate the block, it will evaluate to a true object, which will then know how to respond:
[stringOne = stringTwo] value ifTrue:[myNumber := 20]
Or what you should really do, as others have pointed out:
stringOne = stringTwo ifTrue:[myNumber := 20]
both of which evaluates stringOne = stringTwo to true before sending ifTrue:[...] to it.
[stringOne = stringTwo] is a block, not a boolean. When the block is invoked, perhaps it will result in a boolean. But you are not invoking the block here. Instead, you are merely causing the block to be the receiver of ifTrue.
Instead, try:
(stringOne = stringTwo) ifTrue: [
myNumber := 20 ].
Should you be blocking the comparison? I would have thought that:
( stringOne = stringTwo ) ifTrue: [ myNumber := 20 ]
would be enough.
but I seem to be doing something wrong
Given that you are using VisualWorks your install should include a doc folder.
Look at the AppDevGuide.pdf - it has a lot of information about programming with VisualWorks and more to the point it has a lot of introductory information about Smalltalk programming.
Look through the Contents table at the beginning, until Chapter 7 "Control Structures", click "Branching" or "Conditional Tests" and you'll be taken to the appropriate section in the pdf that tells you all about Smalltalk if-then-else and gives examples that would have helped you see what you were doing wrong.
I would like to add the following 50Cent:
as blocks are actually lambdas which can be passed around, another good example would be the following method:
do:aBlock ifCondition:aCondition
... some more code ...
aCondition value ifTrue: aBlock.
... some more code ...
aBlock value
...
so the argument to ifTrue:/ifFalse: can actually come from someone else. This kind of passed-in conditions is often useful in "..ifAbsent:" or "..onError:" kind of methods.
(originally meant as a comment, but I could not get the code example to be unformatted)