Jump to content

Static & Global


DXRW4E
 Share

Recommended Posts

DatMCEyeBall,

Do you actually run these code snippets before posting them and confusing the hell out of everyone? :huh:

Nope, I'm using my phone.

"Just be fred, all we gotta do, just be fred."  -Vocaliod

"That is a Hadouken. A KAMEHAMEHA would have taken him 13 days and 54 episodes to form." - Roden Hoxha

@tabhooked

Clock made of cursors ♣ Desktop Widgets ♣ Water Simulation

Link to comment
Share on other sites

I believe 'Static' just implies the variable exists for the duration of the script. Because you can't go up one level from global scope, static global variables do not retain their original assigned value in the same way that static local variables do when you exit a function.

Edited by czardas
Link to comment
Share on other sites

Nope, I'm using my phone.

Seriously? Next time add a warning you haven't tested and also don't imply it's the version of AutoIt we're using, because that's also insinuating you have tested as well.

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

  • Moderators

DatMCEyeBall,

 

Nope, I'm using my phone

Then please do us all a favour and do not post untested code snippets again when there is a serious discussion ongoing - particularly when it is a subject about which you evidently have absolutely no understanding at all. :naughty:

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

Static variables are to be used only in a function, what they're for is so that if you declare a variable as a static variable in a function when you leave that function the variable retains its value. Global statics make absolutely no sense, because globals always retain their values no matter where you are in the script. Static variables are not constants, they're just local variables that don't lose their contents when the function ends. Any other use is a misuse of the variable typing.

 

The second example in the help file demonstrates it well. Here's a modified version that also demonstrates how a Global isn't changed by the Local Static variable. BUT take note, the variable referenced right after the Func line, and before the Local declaration line is the GLOBAL variable of the same name.

 

#include <MsgBoxConstants.au3>
Global $vVariableThatIsStatic = 0

Example()

Func Example()
    SomeFunc() ; This will display a message box of 1, 1.
    SomeFunc() ; This will display a message box of 1, 2.
    SomeFunc() ; This will display a message box of 1, 3.
EndFunc   ;==>Example

Func SomeFunc()
    ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : THIS IS THE GLOBAL VARIABLE $vVariableThatIsStatic = ' & $vVariableThatIsStatic & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
    ; This initialises a Static variable in Local scope. When a variable is declared just in Local scope (within a Function,)
    ; it's destroyed when the Function ends/returns. This isn't the case for a Static variable. The variable can't be
    ; accessed from anywhere else in the script apart from the Function it was declared in.
    Local Static $vVariableThatIsStatic = 1
    ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $vVariableThatIsStatic = ' & $vVariableThatIsStatic & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
    Local $vVariableThatIsLocal = 0
    $vVariableThatIsLocal += 1 ; This will always be 1 as it was destroyed once returned from SomeFunc.
    $vVariableThatIsStatic += 1 ; This will increase by 1.
    MsgBox($MB_SYSTEMMODAL, $vVariableThatIsLocal, $vVariableThatIsStatic)
EndFunc   ;==>SomeFunc

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

Link to comment
Share on other sites

Hang on a second...

Shouldn't static be used in a function where you want the next return value of it to be the same as the last, after it's changed? Global Static just means "Yo, create me a value that's going to be the same, but is still mutable and is available in every scope.". It's not like Java where Static means constant. If you're after that, use a constant. When I write constants, I write them in upper-snake-case. YO_IM_A_CONSTANT.

Edited by James
Link to comment
Share on other sites

Static variables are to be used only in a function, what they're for is so that if you declare a variable as a static variable in a function when you leave that function the variable retains its value. Global statics make absolutely no sense

.I know that my English is not ok, but I think you understand this

yes is right, for the moment only this

Global $sGlobal = "Global text"
Global Static $sStatic = "Global Static text"

Global $sGlobal = "new text" ; $sGlobal's value will be changed to "new text"
Global $sStatic = "new text2" ; No change
MsgBox(0,0,$sStatic)

;~ >Running:(3.3.10.2):C:\Program Files (x86)\AutoIt3\autoit3.exe "C:\Users\DXRW4E\Desktop\New AutoIt v3 Script (2).au3"    
;~ --> Press Ctrl+Alt+F5 to Restart or Ctrl+Break to Stop
;~ "C:\Users\DXRW4E\Desktop\New AutoIt v3 Script (2).au3" (5) : ==> Cannot make static variables into regular variables.:
;~ Global $sStatic = "new text2"
;~ Global ^ ERROR
;~ ->11:10:36 AutoIt3.exe ended.rc:1
;~ >Exit code: 1    Time: 0.423
but may do so, in order to work as they should, can not I speak with competence regarding C because I do not know much about C, but in C sees them Global Static seeuse only the files where they are being declared, in autoit this can be done with Au3Check and some (Optional) directive or something like that, where indicate the names of the functions that seeuseeditchange that variable

 

Ciao.

 

C++ Complete Reference - Herbert Schildt (4rd Edition)

static Global Variables

Applying the specifier static to a global variable instructs the compiler to create a

global variable that is known only to the file in which you declared it. This means

that even though the variable is global, routines in other files may have no knowledge

of it or alter its contents directly, keeping it free from side effects. For the few situations

where a local static variable cannot do the job, you can create a small file that contains

only the functions that need the global static variable, separately compile that file, and

use it without fear of side effects.

To illustrate a global static variable, the series generator example from the previous

section is recoded so that a seed value initializes the series through a call to a second

function called series_start( ). The entire file containing series( ), series_start( ), and

series_num is shown here:

/* This must all be in one file - preferably by itself. */

static int series_num;

void series_start(int seed);

int series(void);

int series(void)

{

series_num = series_num+23;

return series_num;

}

/* initialize series_num */

void series_start(int seed)

{

series_num = seed;

}

so has much sense OK

 

concrete example see my INI File Processing Functions '?do=embed' frameborder='0' data-embedContent>> I have a handle them

;;;; DO NOT EVER USE\CHANGE\EDIT THESE VARIABLES ;;;;
;;;;  THESE VARIABLES ARE USED INTERNALLY ONLY   ;;;;
Global Static $INI_NULL_REF = Null
Global Static $_HINI[11][11] = [[10, 0]]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

 

I do not want users to accidentally change the $_HINI OK

 

There are lots and lots of other scenarios that require or need to use a Global Static, or better to say when a Global Static solves many situations, and since autoit does not support pointers, is very useful to have at least the Global Static

 

Ciao.

Edited by DXRW4E

apps-odrive.pngdrive_app_badge.png box-logo.png new_logo.png MEGA_Logo.png

Link to comment
Share on other sites

Hang on a second...

Shouldn't static be used in a function where you want the next return value of it to be the same as the last, after it's changed? Global Static just means "Yo, create me a value that's going to be the same, but is still mutable and is available in every scope.". It's not like Java where Static means constant. If you're after that, use a constant. When I write constants, I write them in upper-snake-case. YO_IM_A_CONSTANT.

*YO_IMA_CONTSTANT_DAWG

"Just be fred, all we gotta do, just be fred."  -Vocaliod

"That is a Hadouken. A KAMEHAMEHA would have taken him 13 days and 54 episodes to form." - Roden Hoxha

@tabhooked

Clock made of cursors ♣ Desktop Widgets ♣ Water Simulation

Link to comment
Share on other sites

Then you need to use the Const keyword.

I think many still have not really understood the function Static, and the real Global Static, they are not Const???, we are completely out of context here

@All

I am not here to give lessons (would be nice, but I'm not so good), or just asked for help, because I need Global Static , and as I believe do not need a lot of work to enable it in Au3Check, or simply asked if it is possible to add, nothing else

Ciao.

Edited by DXRW4E

apps-odrive.pngdrive_app_badge.png box-logo.png new_logo.png MEGA_Logo.png

Link to comment
Share on other sites

I understood what you were saying, and I also understand that you're thinking about it incorrectly.

Static variables can not be Const.

As has been mentioned a couple of times already, you want a constant not a static.

Also from the help file.

 

If the scope specifier Global is used, then the static variable is visible and usable in all parts of the script; in this regard, a Global Static has very little difference from a Global variable.

Whether that last part means that there's no difference or if there is a notable difference I don't know, I can't seem to find any instances where making a Global static has any change from just making it a Global.

Also, when you declare an array as a constant, you have to assign every element on the declaration line, you can't change the values in any element later because you made it a constant.

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

Link to comment
Share on other sites

You could add a line at the top of every function in the UDF to reassign the variable to equal a constant (using a second variable). This would be the equivalent of file scope.

Edit

Sorry, I misunderstood static, only having used it once without actually modifying the value. You would actually need to include a function with Static Local variables to call and overwrite their global counterparts. Same principle but more ugly. :wacko:

Edited by czardas
Link to comment
Share on other sites

Basically, Static in AutoIt performs a different function to that in C and Java.

is the same for all, only that the AutoIt compiler is not that of the "C" and "java", and this is understandable is everything Ok but according to my suggestion, a certain thing you can do perfectly in AutoIt, need just that when Au3Check load a file, take all the names of the functions in that file, and then see if there are Gobal Static, and get to know them only in those functions that file, or add a directive, where to put the names of the functions where seeuseedit that Global Static, nothing else

 

Ciao.

Edited by DXRW4E

apps-odrive.pngdrive_app_badge.png box-logo.png new_logo.png MEGA_Logo.png

Link to comment
Share on other sites

In AutoIt, static means the constructor is called only once and the destructor only called at program termination. From this point of view, global static and global are effectively identical.

What the OP seems to mean in his first post is that he would like to restrict the scope of global static to an enumerated set of functions by way of a directive.

I'd rather have file scope, halas that would mean a fundamental rework of the tools unlikely to happen anytime soon. Masquerading file scope à la czardas (posted above) is kind of horrible.

What could be a way to introduce file scope is instead to make that block scope, with e.g. BEGIN and END statements. Any local variable within would be visible only in its block. That would preserve the external tools strategy and "compiler" structure.

Edited by jchd

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

You could add a line at the top of every function in the UDF to reassign the variable to equal a constant. This would be the equivalent of file scope.

I said here before

this is the point how to protect them in UDF, because in personal script does not need not have to do it does not make sense to do it

Ciao.

Edited by DXRW4E

apps-odrive.pngdrive_app_badge.png box-logo.png new_logo.png MEGA_Logo.png

Link to comment
Share on other sites

In AutoIt, static means the constructor is called only once and the destructor only called at program termination. From this point of view, global static and global are effectively identical.

so for the moment, so also help, but I think they can be done much better, with minor improvements or modifications

Ciao.

Edited by DXRW4E

apps-odrive.pngdrive_app_badge.png box-logo.png new_logo.png MEGA_Logo.png

Link to comment
Share on other sites

Of course in my hypothetical BLOCK ... ENDBLOCK structure (names more in the current style), vars local to a function would remain in function scope.

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

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