Sign in to follow this  
Followers 0
GordonFreeman

Doubts about "For"

18 posts in this topic

I normally use:

For $Count = 1 to 100

msgbox(0, "Count", $Count)

but i need use with variables:

For $Variable1 to 100

I wonder if there is some method

this is to reduce code size, and for a better understanding

Thanks for attention!

Share this post


Link to post
Share on other sites



You have 4 "values" in a For statement. The variable to store the current value of the counter, the start value, the end value and - optional - the step size.

I assume you want to use $Variable1 as the start value. So you should use:

For $Count = $Variable1 to 100

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2017-04-18 - Version 1.4.8.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2017-02-27 - Version 1.3.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2015-04-01 - Version 0.4.0.0) - Download - General Help & Support - Example Scripts
Excel - Example Scripts - Wiki
Word - Wiki
PowerPoint (2015-06-06 - Version 0.0.5.0) - Download - General Help & Support

Tutorials:
ADO - Wiki

 

Share this post


Link to post
Share on other sites

GordonFreeman,

You need the full syntax: :)

For <variable> = <start> To <stop> [Step <stepval>]

All you would save with your suggestion is 3 spaces and a start value - given AutoIt's size when compiled is that so much extra? And in many cases you would not want $Variable1 to increase in value as the loop progresses. ;)

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)

$Variable1 = "Hi"

$Variable2 = "My Name is..."

$Variable3 = "Gordon"

For $Count = $Variable1 to 3

msgbox( 0, "", $Count)

Next

I want make it. Sorry if I did something wrong or explained. My natural language is not English.

But return numbers. Help mee

Edited by GordonFreeman

Share this post


Link to post
Share on other sites

#5 ·  Posted (edited)

Gordon, for that you would need to create an array:

Local $var[3]
   $var[0] = "Hi"
   $var[1] = "My Name is..."
   $var[2] = "Gordon"

   For $element in $var
       msgbox(0, "", $element)
   Next
Edited by JLogan3o13

√-1 2^3 ∑ π, and it was delicious!

Share this post


Link to post
Share on other sites

#6 ·  Posted (edited)

GordonFreeman,

To do that you need an array. :)

Global $aVariable[3] = ["Hi", "My Name is...", "Gordon"]

For $i = 0 To 2
    MsgBox( 0, "", $aVariable[$i])
Next

I suggest reading the Arrays tutorial in the Wiki if you are not very used to using them. ;)

Sorry if I did something wrong or explained. My natural language is not English

You did nothing wrong. ;)

M23

JLogan3o13,

Your turn! :)

Edited by Melba23

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

If he could to use variables and use Execute.

$Variable1 = "Hi"
$Variable2 = "My Name is..."
$Variable3 = "Gordon"
For $Count = 1 to 3
MsgBox( 0, "", Execute("$Variable" & $Count))
Next

Adam

Share this post


Link to post
Share on other sites

@Melba

Yours is cleaner, though :)


√-1 2^3 ∑ π, and it was delicious!

Share this post


Link to post
Share on other sites

Ok. but now I have another doubt.

What if I want to store values

$Variable[5]
For $i = 0 to 4
    $Variable[$i] = IniRead( "TEST.INI", "Test", "TestSec" & $i, "Error")
Next

i try it but not work. my script close.

work will that way:

$Variable1 = IniRead( "TEST.INI", "Test", "TestSec1, "Error")
$Variable2 = IniRead( "TEST.INI", "Test", "TestSec2, "Error")
$Variable3 = IniRead( "TEST.INI", "Test", "TestSec3, "Error")
$Variable4 = IniRead( "TEST.INI", "Test", "TestSec4, "Error")
$Variable5 = IniRead( "TEST.INI", "Test", "TestSec5, "Error")

However shorter

I think I can see the error but I'm traveling here to find out how fix

Share this post


Link to post
Share on other sites

[Test]

TestSec1=1

TestSec2=1

TestSec3=1

TestSec4=1

TestSec5=1

would thus be

In fact, "Sec" would be earlier but not in any way no influence the outcome

File name: TESTE.ini

Share this post


Link to post
Share on other sites

Change the line to this:

$Variable[$i] = IniRead( "TEST.INI", "Test", "TestSec" & $i + 1, "Error")

Untested, but you don't have a TestSec0 so this at least aligns your ini file with your code.


If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Share this post


Link to post
Share on other sites

#14 ·  Posted (edited)

Change the line to this:

$Variable[$i] = IniRead( "TEST.INI", "Test", "TestSec" & $i + 1, "Error")

Untested, but you don't have a TestSec0 so this at least aligns your ini file with your code.

really, i forgot

but he not returned to value of others. Just blank values

Edited by GordonFreeman

Share this post


Link to post
Share on other sites

Why not use IniReadSection? But this code (as suggested by BrewManNH) works for me.

#include <Array.au3>

Local $aArray[5]
For $i = 0 to 4
    $aArray[$i] = IniRead(@ScriptDir & "TEST.ini", "Test", "TestSec" & $i + 1, "Error")
Next
_ArrayDisplay($aArray)

_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_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: 04/09/2015

Share this post


Link to post
Share on other sites

Now that I've learned to use the "For" my source was 610 to 140 lines. And i love autoit =D

Share this post


Link to post
Share on other sites

Wow, what a dramatic decrease.


_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_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: 04/09/2015

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  
Followers 0

  • Similar Content

    • nacerbaaziz
      By nacerbaaziz
      hellow guys
      I am a blind young man
      I started a project to make an audio player
      with recorder
      I ended the player and i did not know how to recorder
      This player is Compatible with the blind and visually impaired and ordinary users
      Unfortunately I do not see so I could not merge images and icons
      So I hope you will be able to help me in this matter
      I will bring you the open source project and please help me to add images, icons and recorder, the project is requires easy access in order to be compatible with the screen readers, Please take this into account.
      the software is organized so the recorder is In a special  menu that Contains stop and start and pause and save.
      The same is true for player
      Please help
      And greetings to all
      easy player.zip
    • nlta1992
      By nlta1992
      I want creat GUI, have button 1 to 10, but only use loop for ... to ... step ... next.
      Thanks.
    • digitalexpl0it
      By digitalexpl0it
      Hello,
       
      I am trying to updated a autoit app that moves files from one location to another. What Ia m trying to do is exclude specified sub directories from being moved/copied or files within the sub-folders
      As of now the code doesn't want to execute the nested for loop 
       
      Global $szDrive, $szDir, $szFName, $szExt Global $File = "*" func File_mover($Src,$File,$Dst) ; GET DIRECTORY EXCLUDES ; ###################### ; Create blank 2 dem array Local $ExArray[0][1] ; load ini file Local Const $sFilePath = "exclude.ini" ; Check to see if ini exists Local $iFileExists = FileExists($sFilePath) ; If the INI file is not found, output error message If not $iFileExists Then msgbox(0,"Oh NO!", $sFilePath & " not found!") endif ; Read ini file Local $aArray = IniReadSection($sFilePath, "test") ; Start the array loop If Not @error Then for $i = 1 to $aArray[0][0] ; Add Ini values into array _ArrayAdd($ExArray, $aArray[$i][1]) next endif ; Display array ;_ArrayDisplay($ExArray, "test Label") ProgressOn("Moving Scanned File(s)", "Moving scans into citrix...", "0%") $aFiles = _FileListToArray3($Src, $File, 1, 1, 0, 0) For $i = 1 To $aFiles[0] call("_PathSplit",$aFiles[$i], $szDrive, $szDir, $szFName, $szExt) $SrcFile = $Src & "\" & $szDrive & $szDir & $szFName & $szExt $DstFile = $Dst & "\" & $szDir & $szFName & $szExt $NumFiles = DirGetSize($Src,1) ; If File Exsists copy and rename file If FileExists($DstFile) Then $DstFile = call("_IfIdenticalIncrement", $SrcFile, $DstFile) If $DstFile <> "" Then For $ii = $NumFiles[1] To 100 Step 10 ProgressSet($ii, $ii & "%","Moving Files...") ; Move Scans ; List Dir in srouce dir $dirEx = _FileListToArray($Src,"*",2) If UBound($dirEx) > 1 Then ; Look in the dir list array For $dir In $dirEx ; Find and compaire dir in exclude array For $exclude In $ExArray If ($dir = $exclude) Then ; if exclude dir found go to top loop and skip ContinueLoop 2 EndIf Next FileMove($SrcFile, $DstFile, 8) Next endif Sleep(100) Next EndIf ; File doesnt exists so copy the file over Else For $ii = $NumFiles[1] To 100 Step 10 ProgressSet($ii, $ii & "%","Moving Files...") ; Move Scans ; List Dir in srouce dir $dirEx = _FileListToArray($Src,"*",2) If UBound($dirEx) > 1 Then ; Look in the dir list array For $dir In $dirEx ; Find and compaire dir in exclude array For $exclude In $ExArray If ($dir = $exclude) Then ; if exclude dir found go to top loop and skip ContinueLoop 2 EndIf Next FileMove($SrcFile, $DstFile, 8) Next endif Sleep(100) next EndIf ProgressSet(100, "Scans Moved...Successfully!", "Done!") sleep(2000) ProgressOff() Next endfunc Func _IfIdenticalIncrement($vSrcFile, $vDstFile) Local $Count = 0 ; Get the modified date of the source file. $ScrVer = FileGetTime($vSrcFile, 0, 1) ; To get all elemnt of the distination file (in plan to add incremental number). call("_PathSplit",$vDstFile, $szDrive, $szDir, $szFName, $szExt) ; Loop to increment the name of the file. While FileExists($vDstFile) $Count += 1 $vDstFile = $szDrive & $szDir & $szFName & "(" & $Count & ")" & $szExt WEnd ; If file(1), it assume that is the first copy. If $Count = 1 Then Return $vDstFile ; If file(x-1) is identical then assume the file is already duplicated. ElseIf $ScrVer = FileGetTime($szDrive & $szDir & $szFName & "(" & $Count - 1 & ")" & $szExt, 0, 1) Then Return "" ; Else assume it is a new version. Else Return $vDstFile EndIf EndFunc ;==>_IfIdenticalIncrement  
       
      This part is skipped and not sure why
       
      For $exclude In $ExArray If ($dir = $exclude) Then ; if exclude dir found go to top loop and skip ContinueLoop 2 EndIf Next INI file is this
       
      [test] EXCLUDE1=test1 EXCLUDE2=test2 EXCLUDE3=test3  
    • RyukShini
      By RyukShini
      Opt("WinDetectHiddenText",1) #include <IE.au3> #include <Array.au3> #include <File.au3> #include <MsgBoxConstants.au3> #include <clear.au3> #include <ColorConstants.au3>; Including required files #include <GUIConstantsEx.au3> #include <file.au3> #include <string.au3> Sleep(5000) Local $emails = "email.txt" ;sets file path Local $pwd = "pwd.txt" ;sets file path Local $name = "name.txt" Local $ArrayEmail[57], $ArrayPwd[57], $ArrayName[57] ;declares array _FileReadToArray($emails, $ArrayEmail) ;converts file to array _FileReadToArray($pwd, $ArrayPwd);converts file to array _FileReadToArray($name, $ArrayName);converts file to array Local $url= "https://localhost/signup" Local $oIE = _IECreate($url, 1) $tags = $oIE.document.GetElementsByTagName("a") For $tag in $tags $class_value = $tag.GetAttribute("class") If string($class_value) = "badge-signup-email-link" Then $oCorrectObj = $tag ExitLoop EndIf Next If IsObj ( $oCorrectObj ) Then _IEAction ($oCorrectObj, "click") EndIf Local $name = _IEGetObjByName ($oIE, "fullname") Local $email = _IEGetObjByName ($oIE, "email") Local $password = _IEGetObjByName ($oIE, "password") _IEFormElementSetValue($name, $ArrayName[1]) _IEFormElementSetValue($email, "" & ++1 & $Arrayemail[1]) _IEFormElementSetValue($password, $ArrayPwd[1]) $colTags = _IETagNameGetCollection($oIE, "input") For $oTag In $colTags If $oTag.value = "Sign Up" Then sleep(15000) _IEAction($oTag, "click") _IENavigate($oIE,"javascript:void(0);") ; javascript:void is triggered. EndIf Next I coded this script and silly me forgot to create it in a loop to begin with -.-
      now I have tried While & For loop with counters and what not, but I just can't seem to get it to work.

      Could someone be of assistance?

      Thanks in advance.
    • alien4u
      By alien4u
      I was having some problems with Progressbar with  nested "FOR" Loop but I was using it unnecessarily so I end up with only one "FOR" Loop.

      Here I'm sharing with you two ways of solve the progressbar problem, this is not for advanced users, this is for reference and newbies like me.
      And about the progressbar using GUICtrlSetData() with one FOR Loop and variable cicles(for example cicles base of elements on Array with variable size) you can do it as fallow:
      Note: Does not matter if the Array size is 50 or 5000 the progressbar will work properly.
      $progress = GUICtrlCreateProgress() Local $count = UBound($Array) Local $imove = ((1 / $count) * 100) ; One is because you will SetData to Progress each 1 cicle. Local $itemp = 0 For $i = 0 To UBound($Array) - 1 ; Your Code could be here $itemp += $imove GUICtrlSetData($progress, $itemp) ; Or your code could be here. Next  
      Another way to do it and I think is more elegant or fancy is like this:
      $progress = GUICtrlCreateProgress() Local $itemp = 0 Local $count = 0 Local $intcount = Floor(Ubound($Array)/100) For $i = 0 To UBound($Array) - 1 ; Your Code could be here If Mod($i, $intcount) == 0 Then $count = $count+1 GUICtrlSetData($progress, $count) EndIf ; Or your code could be here. Next
      Kind Regards
      Alien.