Author Topic: Problem with String Concatenation  (Read 13093 times)

AlanJB

  • VIP Member
  • *****
  • Posts: 436
  • VERY old Programmer
    • View Profile
Problem with String Concatenation
« on: May 11, 2016, 14:41:52 »
Apologies if this is a long post for a simple problem, but I wanted to give as much info as possible.

This started as a simple diagnostic exercise to check that I was correctly getting the source paths of all 5 open tabs in the left explorer panel.

The script (note line 6 , beginning "$Paths...") is:
Code: [Select]
@var $Paths = "";
@var $n = 0;
for ( $n=1; $n<6; $n++ )
{
  MC.SetActiveTab PANEL=LEFT TAB={$n};
  $Paths += GetSourcePath() + "\r\n";
}
MessageBox ("Output",$Paths,0)

The Output, as expected, is:
Code: [Select]
C:\Alan\
C:\Zip\
C:\Tools\
C:\Temp\
C:\Users\Alan\

If I change line 6 to:  $Paths += $n + GetSourcePath() + "\r\n";  the output, NOT as expected, is:
Code: [Select]
12345

It seems everything after $n is ignored in the concatenation !?

If I change line 6 to:  $Paths += GetSourcePath() + " " + $n + "\r\n";  the output, again NOT as expected, is:
Code: [Select]
C:\Alan\ 1C:\Zip\ 2C:\Tools\ 3C:\Temp\ 4C:\Users\Alan\ 5

Once again, it seems everything after $n is ignored.  Is this expected behaviour?  Is there a workaround, or am I doing something wrong?

According to the documentation:  "Conversion from string to number and number to string are often done automatically, making it possible to concatenate a number variable or constant to a string."

TIA

Alan

Mathias (Author)

  • Administrator
  • VIP Member
  • *****
  • Posts: 4416
    • View Profile
    • Multi Commander
Re: Problem with String Concatenation
« Reply #1 on: May 11, 2016, 14:53:01 »
I think is because $n is a number, so when you do + it tries to do math

Normally num converts to string automatically. But that is not possible in all situations.

But you can force a number into a string
Code: [Select]
$Paths += numtostr($)n + GetSourcePath() + "\r\n";

AlanJB

  • VIP Member
  • *****
  • Posts: 436
  • VERY old Programmer
    • View Profile
Re: Problem with String Concatenation
« Reply #2 on: May 11, 2016, 23:55:05 »
I guessed that may be the case when further testing (after I posted) showed that if $n was the last argument in the concatenated string, it worked.

numtostring() works fine - thanks.

Luckily, no-one spotted my deliberate (ahem) mistake - the space in "MessageBox (", which will cause the function to fail, of course.  You need to make the script engine smarter to allow for programmers like me  ;D

Thanks again.

Alan