Jump to content

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

remedy conflicts between ahk and environment variables


  • Please log in to reply
2 replies to this topic
shimanov
  • Members
  • 610 posts
  • Last active: Jul 18 2006 08:35 PM
  • Joined: 25 Sep 2005
or... reclaim AHk's variables for your own.

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"


Laszlo
  • Moderators
  • 4713 posts
  • Last active: Mar 31 2012 03:17 AM
  • Joined: 14 Feb 2005
Thanks, Shimanov! The function GetEnv can be really useful.
Does the following get the same results?
GetEnv( VarName )
{
   VarSetCapacity( buffer, 0xFFFF )
   DllCall( "GetEnvironmentVariable", "str", VarName, "str", buffer, "uint", 0xFFFF )
   Return buffer
}


shimanov
  • Members
  • 610 posts
  • Last active: Jul 18 2006 08:35 PM
  • Joined: 25 Sep 2005

Does the following get the same results?


Yes.