czardas

Answers to Exercises for AutoIt

52 posts in this topic

#1 ·  Posted (edited)

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

Share this post


Link to post
Share on other sites



#2 ·  Posted

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  :)

1 person likes this

Share this post


Link to post
Share on other sites

#3 ·  Posted

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


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______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

 

Share this post


Link to post
Share on other sites

#4 ·  Posted (edited)

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

Share this post


Link to post
Share on other sites

#5 ·  Posted (edited)

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

Share this post


Link to post
Share on other sites

#6 ·  Posted (edited)

@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

Share this post


Link to post
Share on other sites

#7 ·  Posted

Hi,

Or just get rid of the variable altogether:

#include <MsgBoxConstants.au3>

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

M23

1 person likes this

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______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

 

Share this post


Link to post
Share on other sites

#8 ·  Posted (edited)

Why not get rid of MsgBoxConstants.au3? o:)

 

Do you want it to run faster in the morning or the afternoon? :geek:

Edited by czardas

Share this post


Link to post
Share on other sites

#9 ·  Posted

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:

 

Share this post


Link to post
Share on other sites

#10 ·  Posted (edited)

@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

Share this post


Link to post
Share on other sites

#11 ·  Posted

guinness would warmly - and rightly - approve  :)

Share this post


Link to post
Share on other sites

#12 ·  Posted (edited)

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

Share this post


Link to post
Share on other sites

#13 ·  Posted (edited)

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

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

Share this post


Link to post
Share on other sites

#14 ·  Posted

Are we going to post the solutions in this thread where everything is not in one place? :)


AutoIt.4.Life Clubrooms - Life is like a Donut (secret key)

Spoiler

My contributions to the AutoIt Community

Some messages & Apologizes:

If I hurt you, Please accept my apologies, I never (regardless of the situation) mean to hurt anybody!!!

Also, I am very busy with my project so I will appear in the last row of the online list, if you want to contact me: Email@TheDcoder.xyz

Or you can have a nice chat with me in freenode, I use the same nick on freenode too!

3fHNZJ.gif

PLEASE JOIN ##AutoIt AND HELP THE IRC AUTOIT COMMUNITY!

Share this post


Link to post
Share on other sites

#15 ·  Posted

Just now, TheDcoder said:

Are we going to post the solutions in this thread where everything is not in one place? :)

It sounds like a plan. :brr:

Share this post


Link to post
Share on other sites

#16 ·  Posted

Maybe we can upload all of the answers as code snippets to a GitHub repository?


AutoIt.4.Life Clubrooms - Life is like a Donut (secret key)

Spoiler

My contributions to the AutoIt Community

Some messages & Apologizes:

If I hurt you, Please accept my apologies, I never (regardless of the situation) mean to hurt anybody!!!

Also, I am very busy with my project so I will appear in the last row of the online list, if you want to contact me: Email@TheDcoder.xyz

Or you can have a nice chat with me in freenode, I use the same nick on freenode too!

3fHNZJ.gif

PLEASE JOIN ##AutoIt AND HELP THE IRC AUTOIT COMMUNITY!

Share this post


Link to post
Share on other sites

#17 ·  Posted

Sure you can. :) Providing that the exercises and solutions are clearly linked to one other.

Share this post


Link to post
Share on other sites

#18 ·  Posted

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.


AutoIt.4.Life Clubrooms - Life is like a Donut (secret key)

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

Share this post


Link to post
Share on other sites

#19 ·  Posted

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


AutoIt.4.Life Clubrooms - Life is like a Donut (secret key)

Spoiler

My contributions to the AutoIt Community

Some messages & Apologizes:

If I hurt you, Please accept my apologies, I never (regardless of the situation) mean to hurt anybody!!!

Also, I am very busy with my project so I will appear in the last row of the online list, if you want to contact me: Email@TheDcoder.xyz

Or you can have a nice chat with me in freenode, I use the same nick on freenode too!

3fHNZJ.gif

PLEASE JOIN ##AutoIt AND HELP THE IRC AUTOIT COMMUNITY!

Share this post


Link to post
Share on other sites

#20 ·  Posted

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


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

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