guides:v1_v2_cheat_sheet

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
guides:v1_v2_cheat_sheet [2023-03-21 16:12] – created iseahoundguides:v1_v2_cheat_sheet [2025-01-13 19:37] (current) – [v1→2 Conversion Cheat Sheet] Add auto-converter widget to page geek
Line 1: Line 1:
-v1 → c2 cheat sheet is a great idea. The purpose wouldn't be to cover eveything, only the important points. Off the top of my head, +====== v1→2 Conversion Cheat Sheet ======
  
-1. Removing legacy assignment with `=`+===== Converter =====
  
-2. Removing `%` force expression syntax+Attempt to convert AHKv1 syntax to AHKv2 using the [[https://www.autohotkey.com/boards/viewtopic.php?f=6&t=25100|AHK-v2-script-converter]] project.
  
-3Functions are commands, and commands are functions. The fiest comma is removed+<converter> 
 +; Requires AutoHotkey v1.1.26+, and the keyboard hook must be installed. 
 +#InstallKeybdHook 
 +SendSuppressedKeyUp(key) { 
 +    DllCall("keybd_event" 
 +        , "char", GetKeyVK(key) 
 +        , "char", GetKeySC(key) 
 +        , "uint", KEYEVENTF_KEYUP := 0x2 
 +        , "uptr", KEY_BLOCK_THIS := 0xFFC3D450) 
 +}
  
-4Building from 3, you can do+; Disable Alt+key shortcuts for the IME. 
 +~LAlt::SendSuppressedKeyUp("LAlt")
  
-    if (3 < 4) +; Test hotkey: 
-        FAIL+!CapsLock::MsgBox % A_ThisHotkey
  
-    FAIL() +; Remap CapsLock to LCtrl in a way compatible with IME. 
-        MsgBox "Function failed+*CapsLock:: 
-    }+    Send {Blind}{LCtrl DownR} 
 +    SendSuppressedKeyUp("LCtrl") 
 +    return 
 +*CapsLock up:: 
 +    Send {Blind}{LCtrl Up} 
 +    return 
 +</converter>
  
-5. Fat arrow syntax allows easy definition of functions+===== General =====
  
-    FAIL() => MsgBox("Function failed")+  - There is no more Auto Execute //section//. Automatic execution starts at the top and goes //around// any defined hotkeys ((And into the ''%%static __New()%%'' of any class definitions)).\\ Get rid of ❌ top-level returns, add ✅ auto-execute code below hotkeys (if you want) 
 +  - You no longer need the boilerplate at the top of each script. ''#NoEnv'', ''SendMode Input'', ''SetWorkingDir %A_ScriptDir%'', and ''SetBatchLines, -1'' are all defaults in v2.\\ Get rid of ❌ boilerplate 
 +  - Legacy assignments (''='') were removed.\\ Change ❌''var = text'' to ✅''var := "text"'' 
 +  - Commands do not support a first comma anymore.\\ Change ❌''Sleep, 1000'' to ✅''Sleep 1000''
 +  - All commands have been turned into functions. Command syntax is just a function call without parentheses (commands can be //any// function, even user defined ones). Consequently, plain text parameters are gone and all parameters are expressions all the time.\\ Change ❌''MsgBox Hello'' to ✅''MsgBox "Hello"'' or ✅''MsgBox("Hello")'' 
 +  - Memory is reserved using ''Buffer()'' objects not ''VarSetCapacity()''. Buffer is an Object, which always pass by reference, so you don't pass binary data by reference anymore. ''VarSetStrCapacity()'' exists but //ONLY// for string optimization.\\ Change ❌''VarSetCapacity(var, capacity, fillByte)'' to ✅''var := Buffer(capacity, fillByte)'' 
 +  - Ampersand (''&'') is no longer the "address of" operator.\\ Change ❌''DllCall(..., "Ptr", &var)'' to ✅''DllCall(..., "Ptr", var)'' (where ''var'' is a ''Buffer'' object) 
 +  - Guis are fully object-oriented, distinguished by variable reference not by name. 
 +  - Multi-value expressions return the last value, not the first value.\\ Change ❌''return (varToReturn, tmp := 1234)'' to ✅''return (tmp := 1234, varToReturn)'' 
 +  - Single-quoted strings can contain text with double quotes. Doubling up quote marks no longer escapes quotes.\\ Change ❌''var := "Some ""quoted"" text"'' to ✅''%%var := 'Some "quoted" text'%%'' or ✅''var := "Some `"quoted`" text"'' 
 +  - Hotkeys are now functions. They do not need a ''return''. You //only// need you to specify global variables that you modify. <code AutoHotkey>s:: { 
 +    global varWritable 
 +    MsgBox "Hi " varReadable 
 +    MsgBox "Bye " (varWritable := "Jeff"
 +}</code> 
 +  - Variables start as ''unset'' (which is a state, not a value). Unset variables throw when read. Unset makes a great default parameter.\\ Change ❌''MyFunc(param1, param2 := "") {...}'' to ✅''MyFunc(param1, param2 := unset) {...}''\\ Change ❌''if (param2 != "")'' to ✅''if IsSet(param2)''\\ Change ❌''var := [1, , 2]'' to ✅''var := [1, unset, 2]''\\ Change ❌''FunctionCall(required1, required2, , optional2)'' to ✅''FunctionCall(required1, required2, unset, optional2)''\\ Change ❌''var := "" ; Empty the variable'' to ✅''var := Unset'' (unless you need ''var'' to be an empty string)
  
-6. v2 has proper support for memory buffers using `Buffer(size)`+**New Stuff**
  
-7Byref has been replaced by `&`+  - For loops can iterate values directlyIn v1, the variable i will return 1, 2, 3... this is not a problem in v2 and will return a, b c.<code AutoHotkey>for v in ["a", "b", "c"
 +    MsgBox v</code> 
 +  - ''ComCall'' can iterate through a virtual function table without 3 ''DllCall''s
  
-8. ComCall can iterate through a virtual function table without 3 DllCalls 
  
-9. The auto execute section has been removed. Instead, any global code is run, including `static __new()`.+===== Functions =====
  
-10Gui has better syntax and uses an OOP approach+  - Functions can read Global Variables by default, but not write to them. 
 +  - ByRef is now done by ampersand, and must be specified by both caller and callee.\\ Change ❌''MyFunc(ByRef a) {...}'' to ✅''MyFunc(&a) {...}''\\ Change ❌''result := MyFunc(a)'' to ✅''result := MyFunc(&a)''
  
-11. Classes now have a `prototype` object. +**New Stuff**
  
-12You can't mix `static` and `instance` methods anymoreStatic methods can only be called `Name_of_class.method()and instance methods can only be called `instance.method()`. You can however bypass this change by calling `Name_of_class.prototype.method()`+  - First class functions are supportedSo you can use ''MsgBox'' as a function reference.<code AutoHotkey> 
 +execute(func
 +    func("a message"
 +
 +execute(MsgBox)</code> In v1, you had to pass ''execute(Func("MsgBox"))''
 +  - Fat arrow syntax allows easy definition of functions and function objects, so long as those functions can be written as a single return statement<code AutoHotkey> 
 +; This code: 
 +;FAIL() 
 +;    MsgBox "Function Failed" 
 +;} 
 +; Can become: 
 +FAIL() => MsgBox("Function failed")
  
-13. You can't use `obj.1` or `obj.2` to access data. You have to use `obj[1]` and `obj[2]`.  +; This code: 
- +;SomeGlobalFunc(x{ 
-14. This is because AHK v2 has better support for data structures. It incluses array() and map().  +;    x *= 5 
- +;    MsgBox "Times 5: " x 
-15. for loops can iterate values directly. In v1, the variable i will return 1, 2, 3... this is not a problem in v2 and will return a, b c.  +;    return x 
- +;} 
- +;FuncObj := Func("SomeGlobalFunc"
-    for i in ["a", "b", "c"] +; Can become (no longer needing global function): 
-        MsgBox %i% +FuncObj := (x) => (x *= 5MsgBox("Times 5: x)x) 
- +</code> 
- +  - Functions can be defined inside functions, forming //Closures////Closures// are like bound functions, but they bind variables by //reference// not //value// meaning they can modify enclosed variables<code AutoHotkey> 
-16v2 supports first class functions. So you can use `MsgBox` as a function referenceFor example,  +closureFactory(valueToBeEnclosed) { 
- +    myClosure(newValue := unset) { 
-    execute(func) { +        return IsSet(newValue? valueToBeEnclosed := newValue : valueToBeEnclosed
-        func("a message")+
     }     }
 +    return myClosure
 +}
 +myFuncObject := closureFactory(24)
 +MsgBox myFuncObject()
 +myFuncObject(25)
 +MsgBox myFuncObject()
 +</code>
  
-    execute(MsgBox) 
  
-In v1, you had to pass `execute(Func("MsgBox"))`+===== Objects =====
  
-17. In multivalue return statementsv1 returns "a"+  - Objects now have specific sub-types''Map'' and ''Array''. \\ Change ❌''var := {"key": value}'' to ✅''var := Map("key", value)'' (unless you are __sure__ you want basic Object not a Map)\\ Keep ✅''var := []'' or ✅''var := Array()'' (both work) 
 +  - Objects now have two key value stores, one for //Properties// and one for //Items//. The basic object only supports Properties, the Map and Array support Items in different ways. Properties should have set literal names, Items can have dynamic names, like from a variable. Properties are accessed by ''object.LiteralName'', Items by ''object[variableName]''. <code AutoHotkey>data := Map("Count", 1234) 
 +MsgBox data.Count ; Access Property "Count" -> 1 
 +MsgBox data["Count"] ; Access Item "Count-> 1234</code>
  
-    return "a", "b", "c" 
  
-v2 would return "c"+===== Classes =====
  
-18. You can use single quotes like `'this'`.  +  - You do not use ''new'' to create a class anymore, you just call it by name.\\ Change ❌''inst := new Class()'' to ✅''inst := Class()'' 
- +  - Classes create both a //Global Object// and a //Prototype// nowThe global object (''ClassName'') holds items that are ''static'', the prototype (''ClassName.Prototype'') is copied to make new instances. In v1, the global object served both purposes
-19Hotkeys are now functions.  +  - You can't mix "static" and "instance" class members anymore. Static members can only be called ''ClassName.Method()'' or ''ClassName.Property'' and instance methods can only be called ''instance.Method()'' or ''instance.Property''. From inside a static method, ''this'' refers to the Global Object. From inside a normal method, ''this'' refers to the instance.\\ To create a static member, put ''static'' before its name. <code AutoHotkey>class Test { 
- +    static Property := 1234 
-    s:: { +    Property := 5768 
-        MsgBox "hi" +    static Method() 
-        MsgBox "bye"+        MsgBox "Static Method: this.Property
     }     }
- +    Method() { 
-You don't need a return anymore+        MsgBox "Instance Method: " this.Property 
- +    } 
-20. You no longer need the boilerplate on top of each v1 script.  +} 
- +Test.Method() Static Method: 1234 
-    #NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases. +Test().Method() Instance Method: 5678</code>
-    #Warn  ; Enable warnings to assist with detecting common errors. +
-    SendMode Input  ; Recommended for new scripts due to its superior speed and reliability. +
-    SetWorkingDir %A_ScriptDir%  Ensures a consistent starting directory. +
- +
-the above is now the default. Also `SetBatchLines -1` is default as well, so your script will run much faster.+