Jump to content
Sign in to follow this  
InunoTaishou

Why does a string used in an expression return 0?

Recommended Posts

I know on other languages when you try to use a string like this

Global $sString = "Some String"

If ($sString) Then
    ; ...
EndIf

The compiler will fail because string cannot be used in an expression where it needs a bool (something along those lines). But I see instances in other languages where using $sString in an expression will work and implicitly use the length of the string (or because there is some value in that variable).

I'm wondering why AutoIt doesn't do the same. If the $sString is used like in my example (or some other expression where it wants a bool type) implicitly use the length of the string instead of the converting to 0?

Share this post


Link to post
Share on other sites

Isn't that what the _IsString(), _IsDeclared(), StringLen() functions are for?  From my logic:

If "Some String" Then ... doesn't really mean anything or maybe my logic is just screwed up :) 

Share this post


Link to post
Share on other sites

But AutoIt implicitly converts any string used in an expression where it wants a true/false to 0 if that string is not a string representation of a number or true/false ("True" or "False"). If it's going to do that why not implicitly convert it to 1 if the string is not "" (empty/null string)?

IsString just checks if the variable is a string (I.e., 32 is not a string but "32" is)

_IsDeclared just checks if the string representation of the variable is declared in the script

and StringLen is what would be used currently

This is how we currently do it

Global $sString = "Some String"

While (StringLen($sString))
    ConsoleWrite($sString & @LF)
    $sString = StringTrimLeft($sString, 1)
WEnd

And this is how we could be doing it

Global $sString = "Some String"

While ($sString)
    ConsoleWrite($sString & @LF)
    $sString = StringTrimLeft($sString, 1)
WEnd

Seems like such an insignificant thing but it's surprisingly useful. I went from C++, VB, AutoIt to Python (where the latter does work) and it's so freaking nice being able to use the string as a boolean in an if statement

Edited by InunoTaishou

Share this post


Link to post
Share on other sites

I used to do that all over the place and am still correcting it when I see it :D

It seems a bit silly to have to write ...

If $sTring <> "" Then

If isEmpty($sTring) Then ... (in some languages)

But I guess there may be good reasons for it...
It's why it's good to first start studying the basics before you start tinkering. I'm still telling myself that every day... ;)

Share this post


Link to post
Share on other sites

I just ran

Global $sString = "Some String"

While ($sString)
    ConsoleWrite($sString & @LF)
    $sString = StringTrimLeft($sString, 1)
WEnd

And it actually worked.... I don't know who did it, I don't know when it happened, but I swear this used to not work.... Strings used to always evaluate to 0 when used in a boolean expression.

Does this work for anyone else?

Share this post


Link to post
Share on other sites

I remember very specifically that it didn't used to work, and was very frustrated by this. Looking back at a few old scripts I had to use things like Stringlen and Not $sString == ""

Share this post


Link to post
Share on other sites

strings still evaluate to 0 in some cases, no?

msgbox("some string" , "some string" , "some string")

 


,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Share this post


Link to post
Share on other sites

maybe?

#include<array.au3>

local $aArray["zero elements please"]
_ArrayDisplay($aArray , ubound($aArray))

 


,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Share this post


Link to post
Share on other sites

Of course you should never rely on undocumented behaviour.

#include<array.au3>

local $aArray["3 elements please"]
_ArrayDisplay($aArray , ubound($aArray))

In this case it certainly appears to be a conversion.

In addition: boolean comparisons between different data types may sometimes lead to (apparently) contradictory results.

Edit: This is also a conversion, and not the result of some default override value.

MsgBox('1 or 2', '', 'meh')

 

Edited by czardas

Share this post


Link to post
Share on other sites

There is no more "contradictory results" than "some cases" or "random conversion behavior".

Well written computer programs are pretty bad at creating non-repeatable surprising behavior, contrary to humans. Instead, they hopefully exhibit very deterministic behavior which we all rely upon, else our lives would turn turmoil.

A string evaluates to its content when used in a string expression (or parameter of a function expecting a string). No surprise here.

It evaluates to a boolean in a boolean context: Flase if the string is empty, True if non-empty.

It evaluates to its numeric conversion (using Number()) when in a numeric context. Here an empty string evaluates to 0.

All of this always behaved the same for decade(s) AFAICT.


This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites

I have shown two cases where a non-empty (or empty) string evaluates to 0, I could understand that being a product of the msgbox function, but the behavior exists with declaring arrays as well.  And that behavior has existed as long as I have been trolling threads regarding magic numbers.

Edited by iamtheky

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Share this post


Link to post
Share on other sites

An dimension index is expected to be numeric, so Number is applied to the string, yielding zero. No surprise here either.


This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites

so this would be an expected solution if I needed arrays from a list?  because formatting seems like an extra rather than necessary step if the behavior is expected, but I never see it in action.

#include<array.au3>

$sList1 = "20 bottles"
$sList2 = "45 plates"
$sList3 = "200 cups"

local $aArray1[$sList1]
local $aArray2[$sList2]
local $aArray3[$sList3]

_ArrayDisplay($aArray1)
_ArrayDisplay($aArray2)
_ArrayDisplay($aArray3)

 

Edited by iamtheky

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Share this post


Link to post
Share on other sites

I don't believe the interpretor would get mad at you if you use that, albeit that useage might surprise future maintainers.


This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites

It's like we've had a breakthrough! Lol (Sorry I'm late, was busy yesterday)

I quite like the

#include<array.au3>

$sList1 = "20 bottles"
$sList2 = "45 plates"
$sList3 = "200 cups"

local $aArray1[$sList1]
local $aArray2[$sList2]
local $aArray3[$sList3]

_ArrayDisplay($aArray1)
_ArrayDisplay($aArray2)
_ArrayDisplay($aArray3)

Then you could give self documenting arrays self documenting values

#include<array.au3>

Global $aBeers["10 draught beers"]
$aBeers["0 Coors"] = "Coors"
$aBeers["1 Fosters"] = "Fosters"
$aBeers["2 Staropramen"] = "Staropramen"
$aBeers["3 Personi"] = "Personi"
$aBeers["4 Fuller’s London Pride"] = "Fuller’s London Pride"
$aBeers["5 Cruzcampo"] = "Cruzcampo"
$aBeers["6 Heineken"] = "Heineken"
$aBeers["7 San Miguel"] = "San Miguel"
$aBeers["8 Stella Artois"] = "Stella Artois"
$aBeers["9 Mockingfish"] = "Mockingfish"

_ArrayDisplay($aBeers)

(I don't drink, beer was just something that came to mind)

Share this post


Link to post
Share on other sites

I said '(apparently) contradictory' results. Anyway, I don't like the numeric conversion of strings (current implementation) because it doesn't differentiate between valid and invalid numbers. The loose conversion is a bit too loose IMO.

Edited by czardas

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By cruisepandey
      Hi, 
      I have a string like this : 
      Global $Msga = "urrent directory is /send.  (Submission of file with log number 29381077284 is confirmed)";
      I want to extract the number 29381077284  from the string. I did StringSplit to split based on "(" and then use space to reach there, But it's not a good choice. 
      Can anyone help me with regular expression to find the number from String using AutoIT. TIA
    • By DannyJ
      I have this example string:
       
      2020-06-08 09:23:33 : abcdefghifjklm How to trim just the right part? Or how to trim this text right to left?
      I want to trim this string right to left until ' : '.
      In ohter words: I need the 'abcdefghifklm' text.
      I have tried StringTrimRight, but that requires 
      The number of characters to trim. Unfortunately StringSplit trims the left part of the strings.
       
       
    • By careca
      This is my take on string triggers, triggers on specific strings.
      Able to simple text pasting,
      opening links (as long as there's a www. http:\\ or https:\\ at the beggining)
      and is able to open applications, if there is a parameter in the parameter field, it uses it.
      Shows your external, lan, and gateway ip's.
      Able to change system volume by a set percentage, reading from the inputbox the number the user sets, if 0 or empty uses system default.
      I made this because the existing string trigger applications didn't do it for me.
      I did this for me, but if someone finds it useful, all the better.
    • By Colduction
      Hi guys!, i have a problem to convert Python code to AutoIt code, in fact i had not coded with Python yet!, this code is about permutation a string's case, i will be happy with your comments :)❤;

      Python code:
       
      # Python code to print all permutations # with respect to cases # Function to generate permutations def permute(inp): n = len(inp) # Number of permutations is 2^n mx = 1 << n # Converting string to lower case inp = inp.lower() # Using all subsequences and permuting them for i in range(mx): # If j-th bit is set, we convert it to upper case combination = [k for k in inp] for j in range(n): if (((i >> j) & 1) == 1): combination[j] = inp[j].upper() temp = "" # Printing current combination for i in combination: temp += i print(temp), # Driver code permute("Hello") # This code is contributed by Sachin Bisht
      My code in AutoIt:
      ; https://www.geeksforgeeks.org/permute-string-changing-case/ _PermuteCase("ABC") Func _PermuteCase($sText) If StringRegExp($sText, "^[A-Za-z]{1,}$") Then Local $iLength = StringLen($sText) ; Get length of the text. Local $iMaxPerm = 2 ^ $iLength ; Number of permutations is 2^n Local $sLow_Text = StringLower($sText) ; Converting string to lower case Local $asChrs = StringToASCIIArray($sLow_Text) ; Split the text into array of chars. For $i = 1 To $iMaxPerm Step 1 For $j = 0 To $asChrs[0] ;................................................... Next Next Else Return SetError(-1, 0, "Error: Input is incorrect!") EndIf EndFunc ;==>_PermuteCase  
       
       
       
       
       
      ====================== SOLUTION by @TheXman ======================
       
    • By jmp
      i am trying to get number from string using this code :
      #include <IE.au3> $oIE = _IEAttach ("Edu.corner") Local $aName = "Student name & Code:", $iaName = "0" Local $oTds = _IETagNameGetCollection($oIE, "td") For $oTd In $oTds If $oTd.InnerText = $aName Then $iaName = $oTd.NextElementSibling.InnerText $iGet = StringRegExpReplace($iaName, "\D", "") EndIf Next MsgBox(0, "", $iGet) it was get number like 52503058
      But, I want to get only student code 5250. (Different student have different code, sometime its 3 digits, Sometime 4)

       
×
×
  • Create New...