Variables do not persist across separate AutoHotkey processes because each script runs in its own isolated memory space. To share data between scripts, you must use Inter-Process Communication (IPC) methods such as writing to a temporary file, using named pipes, or leveraging the Clipboard. This approach ensures that one script can reliably send information to another without relying on non-existent global variable sharing.
Understanding Process Isolation
AutoHotkey scripts are compiled or interpreted as independent executables. When you run script1.ahk and script2.ahk simultaneously, they occupy different segments of your computer's RAM. A variable defined in the first script, such as MyVar := "Hello", exists only within the context of that specific process. If you attempt to access MyVar in the second script, it will be empty or undefined because the operating system prevents direct memory access between unprivileged processes for security reasons.
This isolation is a feature, not a bug, as it prevents one rogue script from crashing or corrupting the state of another. However, it creates a hurdle when you need coordinated behavior, such as having a helper script read a configuration value set by a main launcher script. You cannot simply declare a global variable at the top of your auto-execute section and expect it to be visible elsewhere. Instead, you must establish a communication channel.
Method 1: Using Temporary Files for Simple Data Exchange
The most straightforward method for passing variables between multiple AHK scripts is using a shared text file. This method is reliable, easy to debug, and works across all versions of AutoHotkey. One script writes the variable value to a file, and the other reads it.
To implement this, create a dedicated folder for your IPC files to avoid clutter. In the sending script, use the FileAppend command to write the current value of your variable. For example:
; Script A: Sender
ValueToSend := "UserPreference"
FileAppend, %ValueToSend%, %A_Temp%\AHK_IPC_Value.txt
In the receiving script, use FileRead to retrieve the content. It is crucial to handle potential errors if the file does not exist yet, which might happen if the sender has not run yet.
; Script B: Receiver
ReceivedValue := ""
if FileExist(A_Temp "\AHK_IPC_Value.txt") {
FileRead, ReceivedValue, %A_Temp%\AHK_IPC_Value.txt
MsgBox, The received value is: %ReceivedValue%
} else {
MsgBox, File not found. Sender may not have run yet.
}
This method is synchronous enough for most automation tasks but introduces a slight delay due to disk I/O. For high-frequency updates, consider the clipboard method instead. Note that this technique avoids the pitfalls mentioned in related guides about AutoHotkey Not Sending Commands, where users often confuse syntax errors with logical isolation issues.
Method 2: Leveraging the Clipboard for Quick Transfers
If you need faster transfer speeds and do not mind temporarily overriding the user's clipboard, you can use the built-in clipboard object. This is particularly useful for transferring strings or small amounts of text between scripts instantly.
Be cautious when using this method, as it interrupts the normal clipboard workflow. Always restore the original clipboard content after reading to prevent data loss for the user. Here is how you can safely pass a variable:
; Script A: Sender
OriginalClipboard := ClipboardAll
Clipboard := MyVariable
ClipWait, 1 ; Wait up to 1 second for clipboard to update
; Script B would read Clipboard here
Clipboard := OriginalClipboard ; Restore immediately if possible
In Script B, you would simply read Clipboard into your local variable. This method is effective for immediate handoffs but requires careful timing. If you are dealing with complex inputs, refer to resources on Mastering Multiple Commands on One Line with AutoHotkey to streamline your sender logic.
Method 3: Advanced IPC with Named Pipes
For robust applications requiring real-time bidirectional communication, named pipes are the superior solution. Unlike files, pipes remain open in memory, allowing continuous streams of data. This is ideal for scenarios where one script needs to continuously feed status updates to another.
Creating a named pipe involves using the DllCall function to interact with Windows API functions like CreateNamedPipeW and ConnectNamedPipe. While more complex to implement, it eliminates the latency of file operations. You define a unique pipe name, such as \\.\pipe\MyAHKPipe, and both scripts connect to it. One acts as the server (listener) and the other as the client (sender).
This approach requires handling binary data correctly and managing connection states. It is overkill for simple variable passing but essential for building complex multi-script ecosystems. Ensure you close the pipe handles when scripts exit to prevent resource leaks, similar to best practices outlined in AHK: Waiting for Multiple Keys Pressed, where proper resource management is key to stability.
Frequently Asked Questions
Can I use Global Variables in AutoHotkey?
Global variables are only global within a single script instance. They cannot be accessed by other running scripts because each script has its own separate memory space. You must use IPC methods like files or pipes to share data between processes.
Is there a performance difference between file and clipboard methods?
Yes, the clipboard method is significantly faster than writing to a file because it operates in RAM rather than on the disk. However, the clipboard method is less reliable if the user interacts with their clipboard during the transfer, whereas file-based methods are persistent and safe.
How do I handle concurrent access to the same IPC file?
If multiple scripts try to write to the same file simultaneously, data corruption can occur. To prevent this, use a locking mechanism or ensure that only one script writes at a time. Alternatively, use unique filenames for each transaction to avoid conflicts.
What happens if the sender script crashes before the receiver reads the data?
If using files, the data remains on the disk until deleted, so the receiver can still read it later. If using the clipboard, the old data is lost once overwritten. Named pipes will disconnect, and the receiver should handle the disconnection gracefully by retrying or logging an error.
Can I send complex objects like arrays between scripts?
You can serialize complex data structures into JSON or CSV format and store them in a file or clipboard string. The receiving script must then parse this string back into an array or object. Direct transmission of native AutoHotkey objects is not possible across process boundaries.