There are two functions: ClearVar and GetEnv; and, a demonstration of their effectiveness. Furthermore, it is now possible to retrieve environment variables with characters in the name which are otherwise restricted by AHk's variable naming requirements.
It works by means of bypassing AHk's default behavior of assigning an associated environment variable when an AHk variable is empty. This method ensures internal variable integrity is preserved. It uses a technique similar to that used by "binary support" code.
GetEnv ensures ready access to the environment variable at all times.
MsgBox, % "env var: [" PATH "] ~ " StrLen( PATH ) "`n`nGetEnv = " GetEnv( "PATH" ) PATH = hello MsgBox, % "ahk var: [" PATH "] ~ " StrLen( PATH ) "`n`nGetEnv = " GetEnv( "PATH" ) ClearVar( "PATH" ) MsgBox, % "reclaimed ahk var: [" PATH "] ~ " StrLen( PATH ) "`n`nGetEnv = " GetEnv( "PATH" ) PATH = %PATH% world MsgBox, % "sample ahk var: [" PATH "] ~ " StrLen( PATH ) "`n`nGetEnv = " GetEnv( "PATH" ) PATH= MsgBox, % "restored env var: [" PATH "] ~ " StrLen( PATH ) "`n`nGetEnv = " GetEnv( "PATH" ) return ClearVar( p_name ) { VarSetCapacity( %p_name%, 1, 1 ) pVar := &%p_name% DllCall( "RtlFillMemory", "uint", pVar, "uint", 1, "uchar", 0 ) } GetEnv( p_name ) { buffer_size := DllCall( "GetEnvironmentVariable", "str", p_name, "uint", 0, "uint", 0 ) if ( buffer_size = 0 ) return VarSetCapacity( buffer, buffer_size ) DllCall( "GetEnvironmentVariable", "str", p_name, "str", buffer, "uint", buffer_size ) return, buffer }
The following example demonstrates one known limitation:
MsgBox, % nonenv "test" ; intended: "test", actual: "test" MsgBox, % path "test" ; intended: "test", actual: "" MsgBox, % "" path "test" ; intended: "test", actual: "test" MsgBox, %path%test ; intended: "test", actual: "test"