Jump to content

Answers to Exercises for AutoIt


Recommended Posts

This thread is dedicated to giving answers to exercises posted in another topic. See link:

The following is my suggested solution to the first exercise I posted.



Exercise (see link) - post #8

Solution
1. It is recommended to include libraries at the start of the script.
2. Date.au3 is not required because the code does not use any functions from that library.
3. Although not a mistake, it is good practice to declare variables using Local (or Global sometimes).

So the first two lines of the script should look like this.

#include <MsgBoxConstants.au3>
Local $iHour = @HOUR

Now let's look inside the conditional statement If ... ElseIf ... EndIf.

4. The constant value $MB_OK should only be used for the first parameter of the MsgBox function (this is a mistake).
    Actually the fourth parameter is not needed at all.
5. The keyword Exit should have been placed after the conditional statement: there is no need to duplicate it.
    In fact, Exit is not needed in this example either.

If $iHour >= 12 Then
    MsgBox($MB_OK, "Message", "It's after midday!")
ElseIf $iHour < 12 Then
    MsgBox($MB_OK, 'Message', "It's not yet midday!")
EndIf

Exit ; Not needed because the script terminates at this point anyway.

Now let's think about the logic of the conditional statement. The keyword ElseIf can be replaced with the simpler keyword Else. Also by reversing the statement sequence, we can get rid of the '>=' operator.

#include <MsgBoxConstants.au3>
Local $iHour = @HOUR

If $iHour < 12 Then
    MsgBox($MB_OK, 'Message', "It's not yet midday!")
Else
    MsgBox($MB_OK, "Message", "It's after midday!")
EndIf

Now the code looks clearer, has zero mistakes and conforms to good coding practices. The changes have not altered the behaviour of the script in any way.

Edited by czardas
Link to comment
Share on other sites

Declaring variables Local at the top of the script could be misleading for beginners
"If you declare a variable at the start of your script and outside any functions it exists in the global scope" (help file)
Indeed it does, regardless of the declared scope 
And "You can also assign a variable without declaring it first" (help file)

;Local $txt = "test"  ; works
;Global $txt = "test"  ; works
$txt = "test"   ; works

Display()

Func Display()
   Msgbox(0,"", $txt)  ; $txt always exists in a global scope
EndFunc

All are allowed and correct - and a priori conform to good coding practices  :)

Link to comment
Share on other sites

  • Moderators

mikell,

Quote

Declaring variables Local at the top of the script could be misleading for beginners

I quite agree with this statement - and this was the subject of a very, very lively argument when the Help file examples were being rewritten some years ago. The main argument of one side was that many other languages allow for Local scoping in the main script and doing so encourages "good practice" - the counter argument was that different languages have different syntax in many occasions (e.g. = vs ==) and AutoIt should remain true to itself by declaring main script variables as Global. As you can see by a cursory glance at how the scope of such variables is currently set in the help file, my side lost....

And as for not scoping, I would argue that all variables should be explicitly scoped (even though this is not necessary in the majority of cases) to prevent any confusion.

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

I expected this to crop up. :rolleyes: I believe the distinction and debate to be beyond the scope of the exercise, which was targeted at absolute beginners. Indeed it would be correct to use Global here, although the variable in question holds a pretty much en-passent value: an unlikely candidate for necessitating global implementation IMHO.

Perhaps the subject of variable scope could form the basis of slightly more advanced multiple choice exercise. :)

Edited by czardas
Link to comment
Share on other sites

Not sure this wins a prize for clarity or simplicity, but it is shorter.;)

#include <MsgBoxConstants.au3>

Global $AMorPM = "before"
If @HOUR >= 12 Then $AMorPM = "after"
MsgBox( $MB_OK, "Message", "It's " & $AMorPM & " midday!" )

 

Edited by RTFC
spacing added in code
Link to comment
Share on other sites

@RTFC Ha you reminded me! Indeed there are many solutions. Mine was just a simple solution. Here's a nice version: courtesy of @spudw2k :D

#include <MsgBoxConstants.au3>

Local $sMiddayStatus = (@HOUR >= 12) ? "after" : "not yet"
MsgBox($MB_OK, "Message", "It's " & $sMiddayStatus & " midday!")

 

Edited by czardas
Link to comment
Share on other sites

  • Moderators

Hi,

Or just get rid of the variable altogether:

#include <MsgBoxConstants.au3>

MsgBox( $MB_OK, "Message", "It's " & ((@HOUR > 12) ? ("after") : ("before")) & " midday!" )

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

1 hour ago, Melba23 said:

this was the subject of a very, very lively argument when the Help file examples were being rewritten some years ago.

Melba,
Though I am personally still reluctant about the way it was done (as an even more potentially misleading thing), nonetheless I can understand it.
About scoping when I went to Autoit (as a super beginner) my logic was : Global for a variable to be used outside and inside funcs, Local for variables to be used inside funcs only, and assignment meant Global outside funcs and Local inside funcs
But I agree (globally ? locally ?) with the concept of explicit scoping to prevent confusion  :)

czardas, I would have used Global in your example...
BTW with this kind of example the "for beginners" concept is totally forgotten  :D

MsgBox(0, 'Message', (@HOUR < 12) ? "It's not yet midday!" : "It's after midday!")

The main interest here is that you don't need to care about scopes any more  :whistle:

 

Link to comment
Share on other sites

@czardas:If these examples are supposed to follow best coding practice, then magic numbers are to be avoided, instead using predefined constants, so then you can't get rid of that #include.:P

EDIT: to be honest, I still frequently fall foul of this directive myself, being lazy and all...:D

Edited by RTFC
Link to comment
Share on other sites

Well there is method behind all this, whether it be madness - who knows? Using the keyword Local never constitutes incorrect syntax, and doing so may help to avoid some of the pifalls that beginners encounter due to confusion about scope. Such issues only become apparent once you start to write your own functions. Prior to reaching this stage, pretty much everything is in the global scope, but this is still a puzzle beneath layers. I think most of you spent some time thinking about scope before coming to a deeper understanding of the subject and I believe it's only fair that it be dealt with after some more basic programming concepts are addressed.

Edit: I'd rather stick to following the approved Help File examples regarding syntax.

Edited by czardas
Link to comment
Share on other sites

42 minutes ago, RTFC said:

@czardas:If these examples are supposed to follow best coding practice, then magic numbers are to be avoided, instead using predefined constants, so then you can't get rid of that #include.:P

EDIT: to be honest, I still frequently fall foul of this directive myself, being lazy and all...:D

For foreign beginners the strings are equally as magic, if not moreso. Especially if you are going to add flags, math is universal.

 

MsgBox("Just An OK Button", 'Message', (@HOUR < 12) ? "It's not yet midday!" : "It's after midday!")

 

Edited by iamtheky

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

Link to comment
Share on other sites

Surely for beginners it is better to teach them to use Global at the top of their scripts.

Then later on, they can learn the more intricate benefits of Local.

Make sure brain is in gear before opening mouth!
Remember, what is not said, can be just as important as what is said.

Spoiler

What is the Secret Key? Life is like a Donut

If I put effort into communication, I expect you to read properly & fully, or just not comment.
Ignoring those who try to divert conversation with irrelevancies.
If I'm intent on insulting you or being rude, I will be obvious, not ambiguous about it.
I'm only big and bad, to those who have an over-active imagination.

I may have the Artistic Liesense ;) to disagree with you. TheSaint's Toolbox (be advised many downloads are not working due to ISP screwup with my storage)

userbar.png

Link to comment
Share on other sites

I can volunteer to manage a GitHub repository :). Please let me know if anyone needs a hand :D. Regarding to the link between the exercises and solution, we can follow a naming scheme for the names of the code snippet files (.au3 files).

EasyCodeIt - A cross-platform AutoIt implementation - Fund the development! (GitHub will double your donations for a limited time)

DcodingTheWeb Forum - Follow for updates and Join for discussion

Link to comment
Share on other sites

Probably just a gist rather than a full repo, no?

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

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...