Jump to content

Sky Slate Blueberry Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate
Photo

[SOLVED] Globals not global?


  • Please log in to reply
2 replies to this topic
adrianh
  • Members
  • 616 posts
  • Last active: Apr 07 2016 03:35 PM
  • Joined: 28 Oct 2012
This is very odd. From my understanding of scoping rules, this should work:

globalVar=VAR DEFINED!!
rshift::
msgbox Outside1: %globalVar%
fn1()
return

rctrl::
msgbox Outside2: %globalVar%
fn2()
return

fn1()
{
; shows up as empty
msgbox Inside1: %globalVar%
}
fn2()
{
global
msgbox Inside2: %globalVar%
}
So it looks like I need to make global as default for the function to use a global var? This can't be right. Posted Image

Oh, and why does the code tag in this forum double space everything?

Adrian

my library base
AHK_L is the bomb! With a whole lot of bug fixes, Unicode support, associative array objects, array like objects, classes and variadic functions, why wouldn't you switch?


maul.esel
  • Members
  • 790 posts
  • Last active: Jan 05 2013 09:26 PM
  • Joined: 28 Feb 2011
Global variables in AHK can only be accessed from global scope. Besides making the function assume-global as you mentioned, there are two more ways:
  • Only the global variables in the function you need:
    globalVar := "abc"
    func()
    {
        global globalVar
        MsgBox %globalVar%
    }
  • Latest AHK supports so-called "super-globals":
    [color=red]global[/color] globalVar := "abc"
    func()
    {
        MsgBox %globalVar%
    }

Join the discussion on The future of AutoHotkey
Posted Image Visit me on github Posted Image
Win7 HP SP1 64bit | AHK_L U 64bit

HotKeyIt
  • Moderators
  • 7439 posts
  • Last active: Jun 22 2016 09:14 PM
  • Joined: 18 Jun 2008
That is correct, you can also define only one var to be global:
fn2(){
   global globalVar
;...
Alternatively you can define a var to be global everywhere:
global globalVar=VAR DEFINED!!