Tsukihime Posted April 24, 2011 Share Posted April 24, 2011 (edited) I'm writing a function that checks whether the provided path is a directory or not. It may already exist, I don't know I didn't look through all of the libraries available. func isDir($file) If FileGetAttrib($file) == "D" Then return True EndIf Return False EndFunc This small simple function basically returns True if it's a directory and False otherwise. I have seen the use of special variables like @error set, but I wasn't sure what are the "proper" things I should do when writing a function. Edited April 24, 2011 by Tsukihime Link to comment Share on other sites More sharing options...
Moderators Melba23 Posted April 24, 2011 Moderators Share Posted April 24, 2011 Tsukihime, what are the "proper" things I should do when writing a functionThere are no fixed rules - all you need to do is make clear whether the function was successful or not. The following is my personal interpretation of "best practice": Expected return Success Failure String String "" Number Number 0 or -1 depending on valid return values Array Array "" Boolean True False Special Value 0 (hWnd, Ptr) In all failure cases I would set @error using: Return SetError($iError, $iExtended, Failure_Return) where $iError and $iExtended give information explaining why the function failed to help debugging. If you follow these guidelines you will always have 2 ways to tell that the function has worked or not: - 1. The return value - 2. @errorAs I said these are personal views, but I believe them to be close to a "standard". Please take a look inside the UDFs in my sig to see how I have implemented them in my own functions. M23 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 columnsChooseFileFolder ---- Single and multiple selections from specified path treeview listingDate_Time_Convert -- Easily convert date/time formats, including the language usedExtMsgBox --------- A highly customisable replacement for MsgBoxGUIExtender -------- Extend and retract multiple sections within a GUIGUIFrame ---------- Subdivide GUIs into many adjustable framesGUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView itemsGUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeViewMarquee ----------- Scrolling tickertape GUIsNoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxesNotify ------------- Small notifications on the edge of the displayScrollbars ----------Automatically sized scrollbars with a single commandStringSize ---------- Automatically size controls to fit textToast -------------- Small GUIs which pop out of the notification area Link to comment Share on other sites More sharing options...
monoscout999 Posted April 24, 2011 Share Posted April 24, 2011 (edited) I have seen the use of special variables like @error set, but I wasn't sure what are the "proper" things I should do when writing a function. I think you have to define every error... for ex. ;example $a = isdir("c:\windows") ; case true consolewrite("return value "&$a&" error code "&@error&@crlf) $a = isdir("c:\windows\explorer.exe") ; case false consolewrite("return value "&$a&" error code "&@error&@crlf) $a = isdir("c:\windo\") ; case @error consolewrite("return value "&$a&" error code "&@error&@crlf) ;func func isDir($file) local $fattrib = FileGetAttrib($file) select case $fattrib == "D" ;is a folder return True case $fattrib = "" seterror(1) ; the file/folder doesn´t exists set error code 1 return "" case Else return false ; is NOT a folder endselect EndFunc I don´t know if is the propper way to do it.... but it works Edited April 24, 2011 by monoscout999 Link to comment Share on other sites More sharing options...
Moderators Melba23 Posted April 24, 2011 Moderators Share Posted April 24, 2011 monoscout999Pretty close to what I suggested - but you need to use StringInStr to look for the "D" as you may have other attributes in the return from FileGetAttrib: I would code it like this: ;example $fReturn = isdir("C:\Windows") ; True ConsoleWrite("Return value " & $fReturn & " Error code " & @error & @CRLF) $fReturn = isdir("C:\Windows\Explorer.exe") ; False and @error = 1 ConsoleWrite("Return value " & $fReturn & " Error code " & @error & @CRLF) $fReturn = isdir("C:\Windo\") ; Does not exist and @error = 2 ConsoleWrite("Return value " & $fReturn & " Error code " & @error & @CRLF) ;func Func isDir($sFolder) Local $sAttrib = FileGetAttrib($sFolder) Select Case $sAttrib = ""; the folder does not exist Return SetError(2, 0, False) Case StringInStr($sAttrib, "D") > 0 ;is a folder Return True Case StringInStr($sAttrib, "D") = 0 ;is NOT a folder Return SetError(1, 0, False) EndSelect EndFunc ;==>isDirM23 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 columnsChooseFileFolder ---- Single and multiple selections from specified path treeview listingDate_Time_Convert -- Easily convert date/time formats, including the language usedExtMsgBox --------- A highly customisable replacement for MsgBoxGUIExtender -------- Extend and retract multiple sections within a GUIGUIFrame ---------- Subdivide GUIs into many adjustable framesGUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView itemsGUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeViewMarquee ----------- Scrolling tickertape GUIsNoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxesNotify ------------- Small notifications on the edge of the displayScrollbars ----------Automatically sized scrollbars with a single commandStringSize ---------- Automatically size controls to fit textToast -------------- Small GUIs which pop out of the notification area Link to comment Share on other sites More sharing options...
GEOSoft Posted April 24, 2011 Share Posted April 24, 2011 Of course some of this depends on how you are getting the path. If you use the FileFindFirstFile/FileFindNextFile method then you don't need a function at all to check it; just check for @Extended $sSearch = FileFindFirstFile("*") ;; *.* won't help you here because Windows doesn't respect the dot. If $sSearch <> -1 Then While 1 $hFile = FileFindNextFile($sSearch) If @Error Then ExitLoop If @Extended Then MsgBox(0, "Folder", $hFile & " is a Folder.") WEnd EndIf George Question about decompiling code? Read the decompiling FAQ and don't bother posting the question in the forums.Be sure to read and follow the forum rules. -AKA the AutoIt Reading and Comprehension Skills test.*** The PCRE (Regular Expression) ToolKit for AutoIT - (Updated Oct 20, 2011 ver:3.0.1.13) - Please update your current version before filing any bug reports. The installer now includes both 32 and 64 bit versions. No change in version number. Visit my Blog .. currently not active but it will soon be resplendent with news and views. Also please remove any links you may have to my website. it is soon to be closed and replaced with something else. "Old age and treachery will always overcome youth and skill!" Link to comment Share on other sites More sharing options...
monoscout999 Posted April 24, 2011 Share Posted April 24, 2011 monoscout999Pretty close to what I suggested - but you need to use StringInStr to look for the "D" as you may have other attributes in the return from FileGetAttrib: I would code it like this: M23you have right ... iguess not findig a dir is an error to Link to comment Share on other sites More sharing options...
guinness Posted April 24, 2011 Share Posted April 24, 2011 I know it's been answered but I just couldn't resist! Func _IsFolder($sFolder) If StringInStr(FileGetAttrib($sFolder), "D") Then Return 1 EndIf EndFunc ;==>_IsFolder 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 parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples... Updated: 22/04/2018 Link to comment Share on other sites More sharing options...
wakillon Posted April 24, 2011 Share Posted April 24, 2011 @guinnessI couldn't resist to a shorter version...Func _IsFolder ( $sFolder ) Return StringInStr ( FileGetAttrib ( $sFolder ), "D" ) EndFunc ;==> _IsFolder ( ) AutoIt 3.3.14.2 X86 - SciTE 3.6.0 - WIN 8.1 X64 - Other Example Scripts Link to comment Share on other sites More sharing options...
guinness Posted April 24, 2011 Share Posted April 24, 2011 Stupid me! Why did I add the If ... EndIf Statement???! << Rhetorical question. 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 parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples... Updated: 22/04/2018 Link to comment Share on other sites More sharing options...
monoscout999 Posted April 25, 2011 Share Posted April 25, 2011 jajaja I couldn't resist sorry for the spam! Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now