AHK v1 to AHK v2 conversion tips/changes summary

Discuss the future of the AutoHotkey language
User avatar
jeeswg
Posts: 6904
Joined: 19 Dec 2016, 01:58
Location: UK

AHK v1 to AHK v2 conversion tips/changes summary

07 Sep 2017, 22:13

CONVERSION CHECKLIST

Code: Select all

[updated: 2019-12-03]

AHK V1 TO V2: CONVERSION CHECKLIST

a quick summary featuring most of the changes to look out for

major (general):
commands to functions: function equivalents (you can use function syntax for all commands: 'Cmd(arg1, arg2)')
commands to functions: function-style parameters (parameters have changed, commands are now functions minus the parentheses: 'Cmd arg1, arg2')
commands to functions: no initial comma ('Cmd, arg1, arg2' is not allowed, use 'Cmd arg1, arg2')

minor (general):
remove directives: #NoEnv, #MaxMem
remove directives further: #CommentFlag/#Delimiter/#DerefChar/#EscapeChar, #LTrim
remove commands: SetBatchLines
remove functions: ComObjEnwrap/ComObjMissing/ComObjParameter/ComObjUnwrap
replace variables: ComSpec -> A_ComSpec
characters: "" to `" [note: for two-way compatibility: \x22 for RegEx, and Chr(34) elsewhere]
continuation sections: '=' form removed, options for ':=' form changed slightly
numbers: blank string no longer treated as 0 [e.g. affects var++]
numbers: cannot use 'var + 0 != ""' to check for an integer/float [use 'var is "number"']
ternary operator: must specify all 3 parts: a ? b : c
'var = value' assignments [to 'var := value']
function definitions: '=' not allowed for assigning default parameter values, use ':='

minor (control flow statement specific):
Loop: function-style parameters
Loop: no initial comma
for loop: the temporary key/value variables are restored to their former contents
if var is type: function-style parameter
if: uses expression syntax always
return: a maximum of one parameter
return: the last parameter is returned (rather than the first parameter)

minor (command/function specific):
InStr/SubStr(/RegExMatch/RegExReplace): negative offsets
RegExMatch: CR/LF handling
RegExMatch: returns an object [it used to return multiple strings (a 'pseudo-array') by default]
StrPut: always returns byte count (and never character count)
CONVERSION GUIDE

Code: Select all

[updated: 2019-12-03]

AHK V1 TO V2: CONVERSION GUIDE
HARD TO CONVERT SUMMARY (REQUIRE MANUAL CONVERSION):

The more awkward conversions, i.e. not one-liners that are easily parsed:
- pseudo-arrays to arrays (RegExMatch, StringSplit removed so use StrSplit, WinGetControls/WinGetControlsHwnd/WinGetList)
- SetFormat removed: (use the Format function on individual items, versus a SetFormat mode on all subsequent items)
- return: the last parameter is returned (rather than the first parameter)
- StringXXX commands removed (e.g. StringGetPos, StringReplace, StringSplit)
- SendMessage: the reply is retrieved as the return value of the function, not as the content of ErrorLevel
- MsgBox: the choice is retrieved as the return value of the function, not via IfMsgBox
- SubStr (negative offsets): to retrieve the last n characters use SubStr(var, -n) instead of SubStr(var, 1-n)
- InStr (negative offsets): to search from the last character backwards use InStr(h, n, cs, -1) instead of InStr(h, n, cs, 0)

Other key points:
- 'notification' commands (dialogs) that currently have no replacements: Progress/SplashImage/SplashTextOff/SplashTextOn
- 'if var in/contains' currently have no replacements
- GUI: Gui/GuiControl/GuiControlGet/Menu removed: use objects instead
- objects: ComObjUnwrap and ComObjEnwrap removed
- also removed: #MaxMem, #NoEnv, AutoTrim, SetBatchLines, FileReadLine, IfMsgBox, Transform
- note: Control/ControlGet, Drive/DriveGet, Process and WinGet/WinSet no longer exist, and have been split up into smaller functions, however, when doing automated conversion, these are easy to convert, the exception being the functions that return arrays: WinGetControls/WinGetControlsHwnd/WinGetList
- note: the most awkward parameter changes: MsgBox/InputBox, InStr/SubStr (negative offset), (also: TrayTip, Sort, Loop, RegRead/RegWrite)

Further:
- 'var = value' removed, use 'var := value'
- commands use expression-style parameters, e.g. 'Cmd %var%text' removed, use 'Cmd var "text"'
- if-statements: use expression-style
- ternary operator: must specify the alternative result, see below for alternatives
- double quotes in expressions via "" is not allowed, there are various alternatives including: Chr(34), `", using single quotes instead of double quotes to contain expressions
- changes to continuation sections
- command-line parameters retrieved via A_Args array, not variables (%0% %1% %2% etc)
- for loops restore the value of the key/value variables when the loop completes
- A_Index can be defined outside of a loop, and for/Loop/while restore the value of A_Index on competition
- var++, now fails if variable is blank, workaround: var := var ? var+1 : 1
- 'address := Object(obj)' removed, use 'ObjAddRef(address := &obj)' [note: 'obj := Object(address)' still remains]

==================================================

SOURCES (OFFICIAL):
v2-changes
https://autohotkey.com/v2/v2-changes.htm
AutoHotkey v2 alpha (UPDATES) - Page 2 - AutoHotkey Community
https://autohotkey.com/boards/viewtopic.php?f=37&t=2120&start=20
Parameter order - AutoHotkey Community
https://autohotkey.com/boards/viewtopic.php?f=37&t=30439
Alphabetical Command and Function Index
https://autohotkey.com/docs/commands/
Alphabetical Function Index
https://lexikos.github.io/v2/docs/commands/index.htm

SOURCES (UNOFFICIAL):
list of every command/function/variable from across all versions - AutoHotkey Community
https://autohotkey.com/boards/viewtopic.php?f=7&t=27321&p=131642#p131642
conversion logic, v1 = -> v1 := -> v2, two-way compatibility - AutoHotkey Community
https://autohotkey.com/boards/viewtopic.php?f=37&t=27069&p=127302#p127302
conversion logic, v1 = -> v1 := -> v2, two-way compatibility - Page 5 - AutoHotkey Community
https://autohotkey.com/boards/viewtopic.php?f=37&t=27069&p=139936#p139936
commands as functions (AHK v2 functions for AHK v1) - AutoHotkey Community
https://autohotkey.com/boards/viewtopic.php?f=37&t=29689&p=169307#p169307

==================================================

SYNTAX DEPRECATED IN AHK V1, REMOVED IN AHK V2:
- var = value -> var := value (e.g. var = text -> var := "text") (e.g. var = %var2% -> var := var2)
- var = -> var := ""
- var := -> var := ""
- default parameters in functions are assigned by := not =
in general, in AHK v2, = is always for comparison, := is always for assignment
Func(Arg1, Arg2, Arg3=3, Arg4="d") -> Func(Arg1, Arg2, Arg3:=3, Arg4:="d")
- ternary operator: must specify the alternative result:
var := x>y ? 2 -> var := x>y ? 2 : var
var := x>y ? 2 -> (x>y) ? (var := 2) : 0
var := x>y ? 2 -> (x>y) && (var := 2)
- variable names/function names cannot start with a digit
- variable names can only contain letters/digits/underscore (and non-ASCII characters)
- deref operator removed: vNum := *var -> vNum := NumGet(var, 0, "UChar")
- command-line parameters retrieved via A_Args array, not variables (%0% %1% %2% etc)
- Loop: old-style file/registry loops removed

SYNTAX REMOVED IN AHK V2:
- Var += Value, TimeUnits -> DateAdd
- ... var += 1, D
- ... var := DateAdd(var, 1, "D")
- Var -= Value, TimeUnits -> DateDiff
- ... var -= A_Year, D
- ... var := DateDiff(var, A_Year, "D")

MISCELLANEOUS CHANGES IN AHK V2:
- to use double quotes in an expression, use `" ("" is not available)
- command parameters: now use expression style e.g. 'Cmd "text" var' (cf. 'Cmd text%var%')
- &&/|| (AND/OR) return value: yield the value or 0 (rather than 1 or 0) [|| now works like Elvis operator]
if you want 1 or 0: var := (var1 && var2) -> var := !!(var1 && var2)
- variables (types): pure numbers and strings are now distinct types
- keys (objects): 'stored differently than on v1 in a few cases'
- ControlMove/ControlGetPos/ControlClick: use client coordinates
- `s is available for spaces (cf. `t for tabs)
- can assign: var := "string" or var := 'string'
- slight differences re. continuation sections
- for loops restore the value of the key/value variables when the loop completes
- bitwise-not always 64-bit, a two-way compatible workaround is: ~var -> var ^ -1
- oFile.__Handle renamed to oFile.Handle
- escaping of colons in hotstrings changed (improved)
- Send: {Raw} replaced with {Text}

MINOR CHANGES IN AHK V2:
- if var is type - 'type' is now a function-style parameter
- A_TitleMatchMode - the default is now 'contains' (it was 'starts'), use SetTitleMatchMode in the auto-execute section to override this
- #SingleInstance - when used as '#SingleInstance', without a parameter, the default is now 'force' (it was 'prompt')
- NumGet/NumPut - changed handling of VarOrAddress parameter, when it is a variable that contains a number ('If the variable contains a pure number, that number is assumed to be an address.')

SYNTAX UNCOMFIRED IN AHK V2:
- 'Cmd, Arg1' not allowed, use 'Cmd Arg1'
- 'if var between' removed [no current replacement, <= and >= can be used instead]
- 'if var contains' [will appear in AHK v2]
- 'if var in' [will appear in AHK v2]
- <> removed, use != or !== [it may be restored in AHK v2]

SOME CHANGES FOR AHK V2 THAT WERE LATER REMOVED:
- what I called 'AutoDeref': '"string%var%string"', it was equivalent to '"string" var "string"'
- 'A_MsgBoxResult': proposed variable no longer exists

==================================================

DIRECTIVES REMOVED IN AHK V2:
#AllowSameLineComments
#CommentFlag
#Delimiter
#DerefChar
#EscapeChar
#LTrim
#MaxMem
#NoEnv

==================================================

BUILT-IN VARIABLES REMOVED IN AHK V2:
0, 1, 2 etc -> A_Args object (command line parameters)
A_AutoTrim
A_BatchLines
A_ExitReason
A_FormatFloat
A_FormatInteger
A_IPAddress1 -> SysGetIPAddresses().1
A_IPAddress2 -> SysGetIPAddresses().2
A_IPAddress3 -> SysGetIPAddresses().3
A_IPAddress4 -> SysGetIPAddresses().4
A_LoopFileLongPath -> A_LoopFilePath
A_LoopRegSubKey
A_NumBatchLines
A_OSType
ClipboardAll -> ClipboardAll function
ComSpec -> A_ComSpec
ProgramFiles -> A_ProgramFiles

BUILT-IN VARIABLES ALTERED IN AHK V2:
A_LoopFileFullPath (AHK v1) = A_LoopFilePath (AHK v2)
A_LoopRegKey "\" A_LoopRegSubKey (AHK v1) = A_LoopRegKey (AHK v2)

BUILT-IN VARIABLES NEW TO AHK V2:
A_AllowMainWindow
A_InitialWorkingDir
A_TrayMenu

BUILT-IN VARIABLES IN AHK V2 THAT DON'T BEGIN WITH 'A_':
Clipboard
ErrorLevel
False
True

==================================================

FUNCTIONS DEPRECATED IN AHK V1, REMOVED IN AHK V2:
Asc -> Ord
ComObjEnwrap
ComObjMissing -> m := ComObject(0xA, 0x80020004)
ComObjParameter
ComObjUnwrap
LV_XXX/SB_XXX/TV_XXX functions (GUI functions)
ObjInsert
ObjRemove

FUNCTIONS ALTERED IN AHK V2:
DllCall - disabled unquoted arg and return types
InStr/SubStr/RegExMatch/RegExReplace - negative offset (0 cf. -1)
Object - 'address := Object(obj)' removed, use 'ObjAddRef(address := &obj)'
RegExMatch - outputs to an object only, option to output to a pseudo-array removed
StrPut - always returns byte count (and never character count)

==================================================

COMMANDS DEPRECATED IN AHK V1, REMOVED IN AHK V2 (USE OPERATORS):
EnvDiv - a := a/b (note: issue with 'a /= b' and truncation)
EnvMult - a *= b
IfEqual - if (a = b)
IfGreater - if (a > b)
IfGreaterOrEqual - if (a >= b)
IfLess - if (a < b)
IfLessOrEqual - if (a <= b)
IfNotEqual - if (a != b), if !(a = b)

COMMANDS DEPRECATED IN AHK V1, REMOVED IN AHK V2:
EnvUpdate - SendMessage with WM_SETTINGCHANGE (aka WM_WININICHANGE)
FileReadLine - FileRead and 'Loop Parse'/StrSplit, 'Loop Read', File object and ReadLine
GetKeyState (command) - GetKeyState (function)
IfExist - FileExist
IfInString - InStr
IfNotExist - FileExist
IfNotInString - InStr
IfWinActive - WinActive
IfWinExist - WinExist
IfWinNotActive - WinActive
IfWinNotExist - WinExist
OnExit (command) - OnExit (function) [note: OnExit function must point to a function, not a label]
SetBatchLines - Sleep (every time it's needed)
SetEnv - a := b
SetFormat - Format (every time it's needed)
SoundGetWaveVolume - SoundGet
SoundSetWaveVolume - SoundSet
StringGetPos - InStr
StringLeft - SubStr
StringLen - StrLen
StringMid - SubStr
StringReplace - StrReplace
StringRight - SubStr
StringSplit - StrSplit
StringTrimLeft - SubStr
StringTrimRight - SubStr
WinGetActiveStats - WinGetTitle, WinGetPos
WinGetActiveTitle - WinGetTitle

COMMANDS REMOVED IN AHK V2:
AutoTrim
EnvAdd - a += b, for dates: DateAdd
EnvSub - a -= b, for dates: DateDiff
Gui
GuiControl
GuiControlGet
IfMsgBox - get return value from MsgBox function
Progress
SplashImage
SplashTextOff
SplashTextOn
Transform

COMMANDS RENAMED IN AHK V2:
DriveSpaceFree - DriveGetSpaceFree
FileCopyDir - DirCopy
FileCreateDir - DirCreate
FileMoveDir - DirMove
FileRemoveDir - DirDelete
FileSelectFile - FileSelect
FileSelectFolder - DirSelect
StringLower - StrLower [alternatively use Format]
StringUpper - StrUpper [alternatively use Format]
UrlDownloadToFile - Download
WinMenuSelectItem - MenuSelect

COMMANDS REMOVED (SPLIT) IN AHK V2 (SPLIT INTO SEPARATE FUNCTIONS):
Control (17 subcommands, to 14 functions, 'Check/Uncheck' to 'Checked', 'Enable/Disable' to 'Enabled', 'TabLeft/TabRight' to 'SetTab')
ControlGet (15 subcommands, each to a function)
Drive (4 subcommands, each to a function)
DriveGet (8 subcommands, each to a function) (also: DriveSpaceFree to DriveGetSpaceFree)
Process (5 subcommands, each to a function)
WinGet (14 subcommands, each to a function)
WinSet (11 subcommands, to 10 functions, 'Enable/Disable' to 'Enabled')

COMMANDS: CHANGES IN AHK V2:
FileRead - binary handling changed (cannot use '*c')
IniRead - return default is blank rather than ERROR
SendMessage - the reply is retrieved as the return value of the function, not as the content of ErrorLevel

COMMANDS: PARAMETERS ALTERED/REARRANGED IN AHK V2:
[note: do notify if I've missed anything out here]
ControlMove - parameters altered (more consistent with other ControlXXX/WinXXX functions)
ControlSend - parameters altered (more consistent with other ControlXXX/WinXXX functions)
ControlSendRaw - parameters altered (more consistent with other ControlXXX/WinXXX functions)
ControlSetText - parameters altered (more consistent with other ControlXXX/WinXXX functions)
FileAppend - parameters altered
FileRead - parameters altered
FileSetAttrib - parameters altered
GroupAdd - parameters altered
Input - separate InputEnd
InputBox - parameters altered
MsgBox - parameters altered (note: IfMsgBox removed)
PixelGetColor - uses RGB by default
PixelSearch - uses RGB by default
Random - separate RandomSeed
RegDelete - parameters altered, separate RegDeleteKey
RegRead - parameters altered
RegWrite - parameters altered
Sort - now uses an input var and output var, parameters altered
SysGet - separate 5 MonitorGetXXX functions
TrayTip - parameters altered
WinMove - parameters altered (more consistent with other ControlXXX/WinXXX functions)
WinSetTitle - parameters altered (more consistent with other ControlXXX/WinXXX functions)

==================================================

COMMANDS ETC WHICH CAN BE DISCARDED IN AUTOHOTKEY V1

there are other subtleties, regarding things that can be discarded in AutoHotkey v1, in favour of more forwards-compatible alternatives, mentioned earlier, this is the simple bulk of commands etc which can be discarded

deprecated (commands/control flow statements):
EnvXXX (still OK: EnvAdd/EnvSub for dates, EnvGet/EnvSet)
FileReadLine
GetKeyState command [use function version]
IfWinXXX [use if WinXXX]
IfXXX (still OK: IfMsgBox) [use if]
Loop FilePattern (old syntax) [use Loop Files]
Loop Rootkey (old syntax) [use Loop Reg]
OnExit command [use function version]
SetEnv [use var := value]
SetFormat [use Format]
SoundGetWaveVolume/SoundSetWaveVolume [use SoundGet/SoundSet]
StringXXX (still OK: StringCaseSense/StringLower/StringUpper)
Transform
WinGetActiveStats/WinGetActiveTitle

deprecated (other):
#CommentFlag/#Delimiter/#DerefChar/#EscapeChar
#IfWinXXX [use #If] [note: it is recommended to keep using #IfWinXXX in AHK v1 until #If is optimised in AHK v1]
#LTrim
Asc [use Ord]
ComObjEnwrap/ComObjUnwrap
OnClipboardChange label [use function version]
RegDelete/RegRead/RegWrite (old syntax) [use new syntax]

not deprecated but have an AHK v1 function alternative:
FileGetAttrib - FileExist
StringLower - Format
StringUpper - Format
WinGet-ID - WinExist

==================================================

SUMMARY OF COMMANDS SPLIT IN AHK V2:
Control, Add -> ControlAddItem [name change]
Control, Check -> ControlSetChecked [name change][ControlSetChecked twice]
Control, Choose -> ControlChoose
Control, ChooseString -> ControlChooseString
Control, Delete -> ControlDeleteItem [name change]
Control, Disable -> ControlSetEnabled [name change][ControlSetEnabled twice]
Control, EditPaste -> ControlEditPaste
Control, Enable -> ControlSetEnabled [name change][ControlSetEnabled twice]
Control, ExStyle -> ControlSetExStyle [name change]
Control, Hide -> ControlHide
Control, HideDropDown -> ControlHideDropDown
Control, Show -> ControlShow
Control, ShowDropDown -> ControlShowDropDown
Control, Style -> ControlSetStyle [name change]
Control, TabLeft -> ControlSetTab [name change][ControlSetTab twice]
Control, TabRight -> ControlSetTab [name change][ControlSetTab twice]
Control, Uncheck -> ControlSetChecked [name change][ControlSetChecked twice]

ControlGet, Checked -> ControlGetChecked
ControlGet, Choice -> ControlGetChoice
ControlGet, CurrentCol -> ControlGetCurrentCol
ControlGet, CurrentLine -> ControlGetCurrentLine
ControlGet, Enabled -> ControlGetEnabled
ControlGet, ExStyle -> ControlGetExStyle
ControlGet, FindString -> ControlFindItem [name change, 'get' dropped]
ControlGet, Hwnd -> ControlGetHwnd
ControlGet, Line -> ControlGetLine
ControlGet, LineCount -> ControlGetLineCount
ControlGet, List -> ControlGetList
ControlGet, Selected -> ControlGetSelected
ControlGet, Style -> ControlGetStyle
ControlGet, Tab -> ControlGetTab
ControlGet, Visible -> ControlGetVisible

DriveGet, Capacity -> DriveGetCapacity
DriveGet, Filesystem -> DriveGetFilesystem
DriveGet, Label -> DriveGetLabel
DriveGet, List -> DriveGetList
DriveGet, Serial -> DriveGetSerial
DriveGet, Status -> DriveGetStatus
DriveGet, StatusCD -> DriveGetStatusCD
DriveGet, Type -> DriveGetType
[also: DriveSpaceFree -> DriveGetSpaceFree]

Drive, Eject -> DriveEject
Drive, Label -> DriveSetLabel [name change]
Drive, Lock -> DriveLock
Drive, Unlock -> DriveUnlock

Process, Close -> ProcessClose
Process, Exist -> ProcessExist
Process, Priority -> ProcessSetPriority [name change]
Process, Wait -> ProcessWait
Process, WaitClose -> ProcessWaitClose

WinGet, ControlList -> WinGetControls [name change]
WinGet, ControlListHwnd -> WinGetControlsHwnd [name change]
WinGet, Count -> WinGetCount
WinGet, ExStyle -> WinGetExStyle
WinGet, ID -> WinGetID
WinGet, IDLast -> WinGetIDLast
WinGet, List -> WinGetList
WinGet, MinMax -> WinGetMinMax
WinGet, PID -> WinGetPID
WinGet, ProcessName -> WinGetProcessName
WinGet, ProcessPath -> WinGetProcessPath
WinGet, Style -> WinGetStyle
WinGet, TransColor -> WinGetTransColor
WinGet, Transparent -> WinGetTransparent

WinSet, AlwaysOnTop -> WinSetAlwaysOnTop
WinSet, Bottom -> WinMoveBottom [name change]
WinSet, Disable -> WinSetEnabled [name change][WinSetEnabled twice]
WinSet, Enable -> WinSetEnabled [name change][WinSetEnabled twice]
WinSet, ExStyle -> WinSetExStyle
WinSet, Redraw -> WinRedraw [name change]
WinSet, Region -> WinSetRegion
WinSet, Style -> WinSetStyle
WinSet, Top -> WinMoveTop [name change]
WinSet, TransColor -> WinSetTransColor
WinSet, Transparent -> WinSetTransparent

==================================================

CONTROLXXX AND WINXXX: FUNCTIONS AND INVERSE FUNCTIONS:

(get text)	ControlEditPaste
(get visible)	ControlShowDropDown/ControlHideDropDown
(LB_GETCURSEL/CB_GETCURSEL)	ControlChoose
ControlFindItem/ControlGetList	ControlAddItem/ControlDeleteItem
ControlGetChecked	ControlSetChecked
ControlGetChoice	ControlChooseString
ControlGetCurrentCol	(set position)
ControlGetCurrentLine	(set position)
ControlGetEnabled	ControlSetEnabled
ControlGetExStyle	ControlSetExStyle
ControlGetHwnd	(read-only property)
ControlGetLine	(set text)
ControlGetLineCount	(set text)
ControlGetSelected	(set selection)
ControlGetStyle	ControlSetStyle
ControlGetTab	ControlSetTab
ControlGetVisible	ControlShow/ControlHide

()	WinRedraw
()	WinSetRegion
WinGetControls	()
WinGetControlsHwnd	()
WinGetCount	()
WinGetExStyle	WinSetExStyle/WinSetAlwaysOnTop
WinGetID	()/WinMoveTop
WinGetIDLast	WinMoveBottom
WinGetList	()
WinGetPID		(read-only property)
WinGetProcessName	(read-only property)
WinGetProcessPath	(read-only property)
WinGetStyle/WinGetMinMax	WinSetStyle/WinSetEnabled
WinGetTransColor	WinSetTransColor
WinGetTransparent	WinSetTransparent

==================================================

;TIPS FOR CONVERTING OLD SCRIPTS (ANSI TO UNICODE)

;useful for converting DllCall lines:
;DllCall converter/cleaner (e.g. x32 to x64/x32 two-way compatible) - AutoHotkey Community
;https://autohotkey.com/boards/viewtopic.php?f=6&t=31365

;this will usually involve editing:
;DllCall
;structs: VarSetCapacity, NumGet/NumPut, StrGet/StrPut

;TIPS FOR CONVERTING OLD SCRIPTS (ANSI TO UNICODE)

;GetProcAddress: Str to AStr:
;pFunc := DllCall("kernel32\GetProcAddress", Ptr,hModule, Str,vFuncName, Ptr)
;to: pFunc := DllCall("kernel32\GetProcAddress", Ptr,hModule, AStr,vFuncName, Ptr)

;DllCall: for some dll function names:
;vFuncName "A"
;to: vFuncName (A_IsUnicode?"W":"A")
;or occasionally to: vFuncName (A_IsUnicode?"W":"")
;note: however, in some circumstances 'A' functions will work fine in AutoHotkey Unicode

;for some structs:
;offsets/sizes will have to be adjusted,
;as strings will require twice as many bytes

;TIPS FOR CONVERTING OLD SCRIPTS (32-BIT TO 64-BIT)

;NumGet: the default in AutoHotkey v1.0 was UInt
;in AutoHotkey v1.1 it is UPtr
;if the type was omitted ...
;if UPtr was intended, the line can stay the same
;if UInt was intended, the line should explicitly state UInt
;for some NumGet lines:
;NumGet(&vData)
;to: NumGet(&vData, 0, "UInt")

;NumGet:
;if UInt was used but UPtr was intended
;for some NumGet lines:
;NumGet(&vData, 0, "UInt")
;to: NumGet(&vData, 0, "UPtr")
;or: NumGet(&vData)

;for some structs:
;offsets/sizes will have to be adjusted
;as some 4-byte pointers will be replaced with 8-byte pointers

;some dll function names require a 'Ptr' suffix in x64,
;whereas it should be omitted in x32
;user32\GetClassLong
;user32\GetWindowLong
;user32\SetClassLong
;user32\SetWindowLong

;FURTHER POINTS

;other commands affected by Unicode/ANSI differences:
;Transform, Unicode
;PostMessage/SendMessage
;Chr and Asc/Ord

;AHK v1.1 additions:
;DllCall: AStr/WStr, Ptr/UPtr
;variables: A_IsUnicode, A_PtrSize

;[AHK v1.0 v. v1.1]
;Script Compatibility
;https://autohotkey.com/docs/Compat.htm

==================================================
FOR LOOP
An example to demonstrate how temporary variables are treated in a for loop in AHK v1/v2.

Code: Select all

;AHK v1 (temporary contents persist)
vValue := "hello"
for vKey, vValue in ["a", "b", "c"]
	MsgBox, % vValue
MsgBox, % vValue ;c

;AHK v2 (original contents restored)
vValue := "hello"
for vKey, vValue in ["a", "b", "c"]
	MsgBox(vValue)
MsgBox(vValue) ;hello
IF VAR IS TYPE (TWO-WAY COMPATIBLE)

Code: Select all

;AHK v1:
if var is number
if var is %type%

;AHK v2:
if var is "number"
if var is type

;two-way compatible:
;static:
number := "number"
if var is number
;dynamic:
type := "number"
%type% := type
if var is %type%
STRINGSPLIT TO LOOP (TWO-WAY COMPATIBLE)

Code: Select all

var := "abc,def,ghi"
StringSplit, var, var, % ","
MsgBox, % Format("{} {} {} {}", var0, var1, var2, var3)

var := "abc,def,ghi"
Loop Parse, var, % "," ;string split
	var%A_Index% := A_LoopField, var0 := A_Index
MsgBox, % Format("{} {} {} {}", var0, var1, var2, var3)

for _, vField in StrSplit(var, ",")
	var%A_Index% := vField, var0 := A_Index
MsgBox, % Format("{} {} {} {}", var0, var1, var2, var3)
LINKS

[converters]
AHK v1 to AHK v2 converter - AutoHotkey Community
https://autohotkey.com/boards/viewtopic.php?f=37&t=36754
DllCall converter/cleaner (e.g. x32 to x64/x32 two-way compatible) - AutoHotkey Community
https://autohotkey.com/boards/viewtopic.php?f=6&t=31365

[compatibility functions]
commands as functions (AHK v2 functions for AHK v1) - AutoHotkey Community
https://autohotkey.com/boards/viewtopic.php?f=37&t=29689
objects: backport AHK v2 Gui/Menu classes to AHK v1 - AutoHotkey Community
https://autohotkey.com/boards/viewtopic.php?f=37&t=43530

[changelogs etc AHK v1.1/v2]
Changes & New Features | AutoHotkey
https://autohotkey.com/docs/AHKL_ChangeLog.htm
AutoHotkey v2 alpha (UPDATES) - AutoHotkey Community
https://autohotkey.com/boards/viewtopic.php?f=37&t=2120
v2-thoughts
https://autohotkey.com/v2/v2-thoughts.htm
v2-changes
https://autohotkey.com/v2/v2-changes.htm
Lexikos (Steve Gray) · GitHub
https://github.com/Lexikos
Last edited by jeeswg on 03 Dec 2019, 00:13, edited 43 times in total.
homepage | tutorials | wish list | fun threads | donate
WARNING: copy your posts/messages before hitting Submit as you may lose them due to CAPTCHA
User avatar
jNizM
Posts: 2538
Joined: 30 Sep 2013, 01:33
GitHub: jNizM
Contact:

Re: AHK v1 to AHK v2 conversion tips/changes summary

08 Sep 2017, 00:57

Why do you post the half stuff from here (https://autohotkey.com/v2/) into here... even if v2 is not finished at all :think:
Next question.. why do you open mutliple threads about v1 to v2 conversion / changes? :think:

Also I dont see a reason why people should care v2 changes, if it's not finshed and there is not a stable build
The current alpha release is usable, but some features, behaviour or syntax may be altered in the next release or future releases.
[AHK] 1.1.30.03 x64 Unicode | [WIN] 10 Pro (Version 1909) x64 | [GitHub] Profile
Donations are appreciated if I could help you
User avatar
jeeswg
Posts: 6904
Joined: 19 Dec 2016, 01:58
Location: UK

Re: AHK v1 to AHK v2 conversion tips/changes summary

08 Sep 2017, 02:53

People asked me for a summary of what would be involved in converting to AHK v2. I wanted one easy-to-find thread. And further to that, this is basically the post I would have wanted when I wanted to know what would be involved in AHK conversion.

There's a difference between understanding what's involved, and writing a script that automates parts of it (most of it) for you. Hence separate threads.

Well it's interesting, there seem to be two distinct camps. Why ARE you using AHK v2 already? Why AREN'T you using AHK v2 already? Perhaps we can find some people of the contrary opinion and get a little argument going. I'm somewhere in the middle.

My opinion is that AHK v2 was complete enough when I started investigating it, to make it worthwhile to begin work on conversion scripts and understanding the changes. Furthermore I was working on AHK v1 function versions of AHK v1 commands, but it appeared wise to modify this slightly to make it AHK v1 function versions of AHK v2 functions.

Fundamentally though, if you know what the changes will be, you can write your AHK v1 scripts in a way that will make them easier to convert later. This is really important, and a big motivation for the guide above.

One thing that I've done which is quite important, is to distinguish between conversion relating to AHK v1 deprecated practices to AHK v1 preferred practices, as opposed to the pure AHK v1 to AHK v2 conversion. Most of the hard-to-convert stuff is actually moving from deprecated AHK v1 practices to newer AHK v1 practices.
homepage | tutorials | wish list | fun threads | donate
WARNING: copy your posts/messages before hitting Submit as you may lose them due to CAPTCHA
just me
Posts: 6567
Joined: 02 Oct 2013, 08:51
Location: Germany

Re: AHK v1 to AHK v2 conversion tips/changes summary

08 Sep 2017, 03:08

:arrow: Changes from v1.1 to v2.0
Do you think your version is better?
User avatar
jeeswg
Posts: 6904
Joined: 19 Dec 2016, 01:58
Location: UK

Re: AHK v1 to AHK v2 conversion tips/changes summary

08 Sep 2017, 03:40

It wasn't my intention to produce something 'better' than that webpage.

Is there a way to check when it was updated? Obviously being more up-to-date can be an advantage.

I have various bits of information that aren't there. Also, there is the emphasis on pointing out AHK v1 good/bad practices, and how *that* is actually the harder part of converting. There is a focus on what you need to do to convert, versus what is the nature of AHK v1 versus v2. Sometimes shorter is better, more focused/prioritised, easier to reread, sometimes longer is better, more detail, more complete. It is a great link, I learnt the core, maybe 80% or more, of what I needed to know about conversion from there. And I did mention it in my guide.
homepage | tutorials | wish list | fun threads | donate
WARNING: copy your posts/messages before hitting Submit as you may lose them due to CAPTCHA
User avatar
Maestr0
Posts: 81
Joined: 05 Dec 2013, 17:43

Re: AHK v1 to AHK v2 conversion tips/changes summary

28 Sep 2019, 02:06

Such negativity, what a way to live your life. Anyway, nice idea, jeeswg! Should help some people if you can get it working!
SOTE
Posts: 858
Joined: 15 Jun 2015, 06:21

Re: AHK v1 to AHK v2 conversion tips/changes summary

01 Dec 2019, 03:25

jeeswg wrote:
08 Sep 2017, 02:53
Fundamentally though, if you know what the changes will be, you can write your AHK v1 scripts in a way that will make them easier to convert later. This is really important, and a big motivation for the guide above.
I think this point should not be underestimated. The more AHK v1 users are using code that is closer to AHK v2, the easier the jump and the more likely AHK v2 will be mostly embraced, instead of splitting the user base or causing forks. AHK v1 to AHK v2 summaries, checklists, or tips are helpful.
User avatar
kczx3
Posts: 933
Joined: 06 Oct 2015, 21:39

Re: AHK v1 to AHK v2 conversion tips/changes summary

01 Dec 2019, 09:54

SOTE wrote:
01 Dec 2019, 03:25
jeeswg wrote:
08 Sep 2017, 02:53
Fundamentally though, if you know what the changes will be, you can write your AHK v1 scripts in a way that will make them easier to convert later. This is really important, and a big motivation for the guide above.
I think this point should not be underestimated. The more AHK v1 users are using code that is closer to AHK v2, the easier the jump and the more likely AHK v2 will be mostly embraced, instead of splitting the user base or causing forks. AHK v1 to AHK v2 summaries, checklists, or tips are helpful.
I think this would be a good reason to start removing deprecated features in v1 gradually so that users will have o use more similar functions/concepts that v2 will use
guest3456
Posts: 2796
Joined: 09 Oct 2013, 10:31

Re: AHK v1 to AHK v2 conversion tips/changes summary

01 Dec 2019, 10:12

kczx3 wrote:
01 Dec 2019, 09:54
I think this would be a good reason to start removing deprecated features in v1 gradually so that users will have o use more similar functions/concepts that v2 will use
i disagree, this will break existing v1 scripts on newer v1 versions

swagfag
Posts: 3086
Joined: 11 Jan 2017, 17:59

Re: AHK v1 to AHK v2 conversion tips/changes summary

01 Dec 2019, 11:00

i think its pointless to try this. nothing about forcing one to dust off their 12yo ahkbasic script just to replace a bunch of <>, ifEquals and SetFormats will even remotely begin approaching familiarizing them with v2 concepts
if u want to make urself familiar with v2, u need to start coding in v2. and for that to happen, one would have to bring v2 to the forefront and cease with the doom and gloom "every update will break yo scripts" rhetoric, thats regularly being touted all over
SOTE
Posts: 858
Joined: 15 Jun 2015, 06:21

Re: AHK v1 to AHK v2 conversion tips/changes summary

01 Dec 2019, 12:22

guest3456 wrote:
01 Dec 2019, 10:12
kczx3 wrote:
01 Dec 2019, 09:54
I think this would be a good reason to start removing deprecated features in v1 gradually so that users will have o use more similar functions/concepts that v2 will use
i disagree, this will break existing v1 scripts on newer v1 versions
I agree with guest3456 on this point. Removing deprecated features will hurt users. In addition, if we are removing deprecated features from AHK v1, then arguably there is no need for AHK v2. Because new AHK v1 versions will not be backwards compatible with older versions.

Furthermore, being so quick to jump to AHK v2, just for the fun of "the new toy" can be devastating to the community. Think of all the libraries, tools, tutorials, examples, and scripts written in AHK v1, that now become "worthless". Who will rewrite all those libraries and scripts from AHK v1 to AHK v2? In most cases, even people that code in AHK v2, will not go back and rewrite their own scripts. The bigger the script, the more work, the less likely to rewrite. The reality check is that most authors won't, so a massive amount of community value becomes lost.

This is why I feel a slow merge (which planned for or not has happened) has the greater benefit. While the versions become closer together, more tools to help conversion, will arguably make the eventual switch more successful. This includes an outright AHK v1 to AHK v2 tool, where if it can't directly convert code, it can suggest changes to make. This can help those that will be rewriting AHK v1 code to AHK v2, and encourage some of the authors who have written popular libraries and scripts.
User avatar
jeeswg
Posts: 6904
Joined: 19 Dec 2016, 01:58
Location: UK

Re: AHK v1 to AHK v2 conversion tips/changes summary

01 Dec 2019, 12:25

kczx3 wrote:
01 Dec 2019, 09:54
I think this would be a good reason to start removing deprecated features in v1 gradually so that users will have [to] use more similar functions/concepts that v2 will use
I've said we could add an option in AHK v1 to #Warn, to: warn against using deprecated practices, when more forwards compatible practices are available.

@swagfag: This option would help with the learning/familiarisation process. And make it quicker/easier to update to AHK v2 later on.
homepage | tutorials | wish list | fun threads | donate
WARNING: copy your posts/messages before hitting Submit as you may lose them due to CAPTCHA
SOTE
Posts: 858
Joined: 15 Jun 2015, 06:21

Re: AHK v1 to AHK v2 conversion tips/changes summary

01 Dec 2019, 13:03

jeeswg wrote:
01 Dec 2019, 12:25
kczx3 wrote:
01 Dec 2019, 09:54
I think this would be a good reason to start removing deprecated features in v1 gradually so that users will have [to] use more similar functions/concepts that v2 will use
I've said we could add an option in AHK v1 to #Warn, to: warn against using deprecated practices, when more forwards compatible practices are available.

@swagfag: This option would help with the learning/familiarisation process. And make it quicker/easier to update to AHK v2 later on.
Seems like a good idea. If a user turns such on, it will show what lines of code are deprecated. I know the help manual has this, put having such a feature built into the AHK v1 Interpreter seems even better. Possibly, #Warn could also be configured to indicate AHK v1 lines of code that aren't compatible with AHK v2. As what is deprecated and what is compatible, can be different.
swagfag
Posts: 3086
Joined: 11 Jan 2017, 17:59

Re: AHK v1 to AHK v2 conversion tips/changes summary

01 Dec 2019, 15:46

jeeswg wrote:
01 Dec 2019, 12:25
#Warn, to: warn against using deprecated practices, when more forwards compatible practices are available.
i guess. people will disable/enable(depending on opt-in/-out) it all the time anyway, but there only so much u can do
SOTE wrote:
01 Dec 2019, 12:22
Furthermore, being so quick to jump to AHK v2, just for the fun of "the new toy" can be devastating to the community.
if u think thats the purpose of v2, to be ur "new toy", then uve missed the point entirely
Think of all the libraries, tools, tutorials, examples, and scripts written in AHK v1, that now become "worthless".
yeah, software changes and now the 100th incarnation of someone's implementation-detail-tightly-coupled tooltip library is all broken. boohoo
Who will rewrite all those libraries and scripts from AHK v1 to AHK v2?
their authors; whoever needs the lib; whoever is bored enough to do so; nobody. who rewrote all ahkbasic libraries to make them x64 unicode compatible? the same applies here
In most cases, even people that code in AHK v2, will not go back and rewrite their own scripts. The bigger the script, the more work, the less likely to rewrite. The reality check is that most authors won't, so a massive amount of community value becomes lost.
the reality check is that whether lexikos barges into this thread right this very second to announce v2's long anticipated departure from alpha or he does so 10 years from now, nothing will change.
libraries will still have to be ported over, new ones will still have to be written from scratch.
the thing we're discussing here is whether starting such a transition now outweighs the downsides of the API changing yet again midway through.
This is why I feel a slow merge (which planned for or not has happened) has the greater benefit. While the versions become closer together, more tools to help conversion, will arguably make the eventual switch more successful.
what are u talking about? what merge has happened? v2 diverges from v1 vastly and in more subtle ways than merely syntax. which is incidentally why i find this idea of a conversion tool a total pipe dream.
SOTE
Posts: 858
Joined: 15 Jun 2015, 06:21

Re: AHK v1 to AHK v2 conversion tips/changes summary

02 Dec 2019, 02:06

swagfag wrote:
01 Dec 2019, 15:46
what are u talking about? what merge has happened? v2 diverges from v1 vastly and in more subtle ways than merely syntax. which is incidentally why i find this idea of a conversion tool a total pipe dream.
I meant similar syntax and abilities between AHK v1 and AHK v2, not an actual merging of source code. This is why AHK v1 has the deprecated syntax warnings in the help file. Hopefully such actions are to make it possible to write AHK v1 scripts in a way that makes it easier to convert them in the future or understand the syntax used in AHK v2.

A conversion tool doesn't have to be perfect, just useful. What it can't convert, it can hopefully make suggestions and link to the help file. I don't think most of the community are advanced or professional level programmers, where switching versions or rewriting scripts will be an easy or fast task. Some scripts can have been tweaked over periods of months, even years, before they became "just right" for their purpose. I think it will be a daunting task for such casual programmers with say scripts of more than 5,000 lines of code or multiple scripts with thousands of lines, to have to convert to AHK v2. This arguably includes some advanced programmers and authors of highly popular tools like AHK Studio, AutoGUI, etc... I think many won't do the conversion, and continue to use AHK v1. Therefore it will probably be best to provide some type of useful incentive or encouragement, which I think a conversion tool is.

Also the circumstances around AHK Basic to AHK v1, is much more different than AHK v1 to AHK v2. According to the public history about AHK Basic, Chris stopped developing completely (kind of retired), so the fork AHK_L (AHK v1) became the official version, as it was continually developed. But debatably that was aided by the web site fracas caused by Polyethene (Titan). Chris appeared to initially hand over the keys (AutoHotkey leadership) to Polyethene, who was developing IronAHK and was trying to reinitiate development of AHK Basic. Possibly IronAHK could have became the official version, or development of AHK Basic restarted. But after the web site "war", Polyethene was kind of voted out, and IronAHK went into hibernation. I mention this, because things could of have gone differently than they are now.

There is nothing stopping a fork of AHK v1, to maintain a backwards compatible version that's continually developed, to oppose AHK v2. Arguably, a lot of users would support that. This is why I think it's better not to provoke a split in the user base, and help make a transition between AHK v1 to AHK v2 be done as smoothly as possible.
User avatar
nnnik
Posts: 4329
Joined: 30 Sep 2013, 01:01
Location: Germany

Re: AHK v1 to AHK v2 conversion tips/changes summary

02 Dec 2019, 07:48

When you have 5000 lines of code you are most likely coding inefficient. While I think that conversion tools will be great for new and less advanced users.
Advanced users may or may not use that tool depending on its quality and completeness. Sadly I havent seen any candidates that come close to the quality that I feel is necessary to make me use it.

Regardless I actually think that the removal of old outdated and often poorly written libraries is one of the advantages of moving to AHK v2.
I still hope that AHK v2 introduces a library manager with sufficient quality standards to make creating libraries really worthwhile again.

Many of the new concepts that were introduced with AHK v2 would mean the entire restructurization of the library in question. At that point a rewrite is usually easier.

V2 is like a fresh start for AutoHotkey I'd hate to make do with libraries that were bodged together out of masses of poor practice and were then poorly translated to AHK v2.
Recommends AHK Studio
SOTE
Posts: 858
Joined: 15 Jun 2015, 06:21

Re: AHK v1 to AHK v2 conversion tips/changes summary

02 Dec 2019, 11:25

nnnik wrote:
02 Dec 2019, 07:48
When you have 5000 lines of code you are most likely coding inefficient.
I think that's an unfair statement. The size of a program can be reflective of the tasks it must handle, therefore it can become large. For Example, the very popular community tool AHK Studio has over 13,000 lines of code. And I would wager that Maestrith is a better programmer than most.
nnnik wrote: While I think that conversion tools will be great for new and less advanced users.
Advanced users may or may not use that tool depending on its quality and completeness. Sadly I havent seen any candidates that come close to the quality that I feel is necessary to make me use it.
I can understand your opinion about that, but if somebody wants to give writing a conversion tool a try, I think we can at least be encouraging to them. And over time, it might turn out to be very useful or even a great tool.
nnnik wrote: Regardless I actually think that the removal of old outdated and often poorly written libraries is one of the advantages of moving to AHK v2.
I still hope that AHK v2 introduces a library manager with sufficient quality standards to make creating libraries really worthwhile again.

Many of the new concepts that were introduced with AHK v2 would mean the entire restructurization of the library in question. At that point a rewrite is usually easier.

V2 is like a fresh start for AutoHotkey I'd hate to make do with libraries that were bodged together out of masses of poor practice and were then poorly translated to AHK v2.
A library manager does look like a good idea. However, the quality of how well written libraries and tools are can be very subjective. A fresh start does not mean that older useful libraries will be rewritten and it's still likely that many valuable resources, tutorials, and tools will be lost and never see a v2 equivalent. Tools or libraries that might not be important to you, might be to other users.

Maybe my previous comments about IronAHK might have ruffled some feathers on another thread, but when I think "fresh start", I visualize something more radical. A version of AutoHotkey that runs on Macs, Androids, and Linux would be refreshingly wonderful. In the case of AHK v1 versus AHK v2, I don't know to what extent "average Joe" will appreciate the differences. And if certain people want to promote how great the differences are between v1 and v2, I would think that conversion tips and conversion tools would be a good place to start.

Return to “AutoHotkey v2 Development”

Who is online

Users browsing this forum: No registered users and 8 guests