Jump to content

Need some help understanding this Ternary operator


 Share

Go to solution Solved by guinness,

Recommended Posts

I have seen the example and I saw a thread on here but it was all very confusing. Could someone give me a brief description of why and how it is useful and a few simple examples that demonstrate different uses of it? I saw somewhere using message boxes as part of it but when I tried using consolewrites nothing worked. I tried to do:

$a = 1
$b = False
$c = 123
$d = 2

$timer = TimerInit()
($a + $d = 3) ? (ConsoleWrite('True' & TimerDiff($timer) & @LF)) : (ConsoleWrite('False' & TimerDiff($timer) & @LF))

I just do not understand it yet, I would appreciate some clarification. Thanks.

Link to comment
Share on other sites

First disable Au3Check and you will see the error disappear, since Au3Check is flagging as an error that it should be used to assign back to a variable (read the error). Use #AutoIt3Wrapper_Run_Au3Check=N at the top of your script.

Now read this...

#cs
    People tend to use ternary as a replacement for If...Else...Then, which can be wrong and is something I am guilty of myself in the past.
    Take for example what you posted above (see the "tided" code below), it's wrong because when you look at it was is different between both ConsoleWrite() calls?
    Correct, only the true and false strings. Now I know someone is going to come in and say well you can do this...

    ConsoleWrite((($iNum1 + $iNum2) = 3) & TimerDiff($hTimer) & @CRLF)

    and while that's correct, what if the output is not true and false? Perhaps it is wind and water, what then? So let me continue with what I was saying.
#ce

Local $iNum1 = 1
Local $iNum2 = 2

Local $hTimer = TimerInit()
Local $vReturn = (($iNum1 + $iNum2) = 3) ? ConsoleWrite('True ' & TimerDiff($hTimer) & @CRLF) : ConsoleWrite('False ' & TimerDiff($hTimer) & @CRLF) ; The error was Au3Check, so just assign the return value of ConsoleWrite() to a variable.

; This is the correct approach with ternary and your example.
ConsoleWrite('My approach: ' & ((($iNum1 + $iNum2) = 3) ? 'True' : 'False') & ' '  & TimerDiff($hTimer) & @CRLF)

; Another usage is assigning on declaration. Which is easier to understand and code? (As coders less typing is always a good thing.)
Local $sEarthOrWind
If ($iNum1 + $iNum2) = 3 Then ; Notice how I encapsulate the expression in parentheses. !IMPORTANT!
    $sEarthOrWind = 'Wind'
Else
    $sEarthOrWind = 'Fire'
EndIf
ConsoleWrite('Variable declaration pt. 1: ' & $sEarthOrWind & @CRLF)

; Or is this?
Local $sEarthOrWindEx = (($iNum1 + $iNum2) = 3 ? 'Wind' : 'Fire')
ConsoleWrite('Variable declaration pt. 2: ' & $sEarthOrWindEx & @CRLF)


; But I digress, as all of this is documented within the Forum plus the Internet. 
Edited by guinness

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

#AutoIt3Wrapper_Run_AU3Check=n
#AutoIt3Wrapper_UseX64=n

Global Const $g__PreferredBitSize = (@AutoItX64 ? 64 : 32)
ConsoleWrite($g__PreferredBitSize & @LF)

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)

Link to comment
Share on other sites

So the only thing I was getting wrong is that if I do not want to disable the checker, I have to assign the whole thing to a variable? Thats not a problem, I would rather have a variable just make it work than have to go disabling some checking feature.

Thanks

Link to comment
Share on other sites

So the only thing I was getting wrong is that if I do not want to disable the checker, I have to assign the whole thing to a variable? Thats not a problem, I would rather have a variable just make it work than have to go disabling some checking feature.

 

Thanks

No. Please read carefully what I wrote, as you said you wanted to understand its usage. Even if you do use that "workaround" it's still wrong and thus there has been a misunderstanding of the usage of ternary. Otherwise you might as well just use If...Else...Then, which if you say is not for you, then I am curious as to why this is? Edited by guinness

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

  • Solution

A good discussion on the subject >> '?do=embed' frameborder='0' data-embedContent>>

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

You're welcome.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

I have a weird thing with this I hope you can help me understand the difference between the two:

This one works and shows the whole path and filename:

ConsoleWrite(@ScriptDir & ((StringMid(@ScriptDir, StringLen(@ScriptDir), 1) <> '\') ? ('\') : ('')) & 'IDCdebug.txt' & @CRLF)

This one only shows the ternary result (either or nothing) even though there is a macro preceeding it with an &:

ConsoleWrite(@ScriptDir & (StringMid(@ScriptDir, StringLen(@ScriptDir), 1) <> '\') ? ('\') : ('') & 'IDCdebug.txt' & @CRLF)

On the help file it does not show that you must enclose the whole over all ternary structure inside brackets, yet in my case it only works when I put the entire thing in brackets. I put each individual component in brackets as shown on the helpfile, so I do not know why I could only get it working by putting the whole thing in brackets additionally.

I would appreciate some clarification on this.

Link to comment
Share on other sites

^^ It's the default operator precedence kicking-in when you fail to be explicit about order in which you want to evaluate the expression. For example, here:

$x = 13 & 4 * 3 / 2 + 7 - 6 / 3 - 4 / 2 * 3 + 32
ConsoleWrite($x & @CRLF)

What's printed to console?

It's simple, be explicit if implicit confuses you.

♡♡♡

.

eMyvnE

Link to comment
Share on other sites

The issue with operator's priority.

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)

Link to comment
Share on other sites

^^ It's the default operator precedence kicking-in when you fail to be explicit about order in which you want to evaluate the expression. For example, here:

$x = 13 & 4 * 3 / 2 + 7 - 6 / 3 - 4 / 2 * 3 + 32
ConsoleWrite($x & @CRLF)

What's printed to console?

It's simple, be explicit if implicit confuses you.

Your example does not help me to understand why my failed (first) attempt does not even show the first macro.

The issue with operator's priority.

Could you explain the concept to me based on my particular example so that I understand why my failed attempt did not even show the initial macro and was replaced only with the ternary result?

Link to comment
Share on other sites

Your example does not help me to understand why my failed (first) attempt does not even show the first macro.

Then maybe you should try more.

 

This:

ConsoleWrite(@ScriptDir & (StringMid(@ScriptDir, StringLen(@ScriptDir), 1) <> '\') ? ('\') : ('') & 'IDCdebug.txt' & @CRLF)
...is shorthand version of this:

If @ScriptDir & (StringMid(@ScriptDir, StringLen(@ScriptDir), 1) <> '\') Then
    ConsoleWrite('\')
Else
    ConsoleWrite(('') & 'IDCdebug.txt' & @CRLF)
EndIf
...which in simplified form, after semantic analysis, can be reduced to (and written as):

ConsoleWrite('\')
Edited by trancexx

♡♡♡

.

eMyvnE

Link to comment
Share on other sites

Then maybe you should try more.

 

This:

ConsoleWrite(@ScriptDir & (StringMid(@ScriptDir, StringLen(@ScriptDir), 1) <> '\') ? ('\') : ('') & 'IDCdebug.txt' & @CRLF)
...is shorthand version of this:

If @ScriptDir & (StringMid(@ScriptDir, StringLen(@ScriptDir), 1) <> '\') Then
    ConsoleWrite('\')
Else
    ConsoleWrite(('') & 'IDCdebug.txt' & @CRLF)
EndIf
...which in simplified form, after semantic analysis, can be reduced to (and written as):

ConsoleWrite('\')

 

Thank you. I believe what you are saying is the initial part @ScriptDir & was being treated as part of the first component of the ternary operation, so the brackets isolate it to the desired components only. This is exactly what I needed. And for the record I do "try" which is why I figured out how to make it work, I just did not understand why it worked and that drove me here to try and get answers so that I know why to do something instead of just what. I hate "Just do it this way" if I do not know the background on the reason why to do things a particular way. So thank you for this latest example, I believe I understand now.

Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...