Get Environment Variable?

BlitzMax Forums/BlitzMax Programming/Get Environment Variable?

Grey Alien(Posted 2006) [#1]
Hi, I've been searching the code archives and looking at the docs for a method to get environment variables in BMax. Does anyone have any code/links? Thanks in advance!


Eikon(Posted 2006) [#2]
Unreliable method 1
Function GetEnv:String(env_var:String)
	Return String(getenv_(env_var))
End Function


Reliable method 2
' Extern
' Function GetEnvironmentVariableA(VarName:Byte Ptr,back:Byte Ptr,size:Short)

Function GetEnvVar:String(VarName:String)
		Local TempBank:TBank = CreateBank(1)
		Local size:Int = GetEnvironmentVariableA(Varname,BankBuf(TempBank),1)
		If size > 0
			ResizeBank(Tempbank,Size+1)
			GetEnvironmentVariableA(Varname,BankBuf(TempBank),Size+1)
		Else
			Return ""
		EndIf
		
		Local tString:String = ""
		Local t:Int
		For t = 0 To BankSize(tempbank)-3
			tString = tString + Chr(PeekByte(tempbank,t))
		Next
		
		ResizeBank(TempBank,0)
		Return tString
End Function
credit to Indiepath on the second one


Grey Alien(Posted 2006) [#3]
thanks dude. Funny I had that second one in BlitzPlus, I think Indiepath must have given it to me for Xmas Bonus and I converted it to BPlus or something, but never kept the BMax original (cos I never owned Bmax at the time). That line under Extern should be uncommented though...


Yan(Posted 2006) [#4]
I've got a feeling that it was originally written in bb anyway as it's a tad 'convoluted' for native BMax code...
Strict

Extern "Win32"
	Function GetEnvironmentVariable(lpName$z, lpBuffer:Byte Ptr, nSize) = "GetEnvironmentVariableA@12"
End Extern

Print GetEnv("USERPROFILE")

End

Function GetEnv$(envVar$)
		Local buff@[64]
		
		Local rtn = GetEnvironmentVariable(envVar$, buff@, buff.length)
		If rtn > buff.length
			buff@ = buff@...]
			rtn = GetEnvironmentVariable(envVar$, buff@, buff.length)
		EndIf
		
		Return string.FromBytes(buff@, rtn)
End Function



Grey Alien(Posted 2006) [#5]
Cool, thanks. I'll now use that one and change the credit to Ian.