Global Variables

Started by mpiaser, July 10, 2013, 04:46:16 PM

Previous topic - Next topic

mpiaser

Is there a way to define a Global Variable in Winbatch.  I would like to be able to set a variable (Debug=Y or N) and be able to reference the variable in all future code include subroutines/functions/etc.

snowsnowsnow

The short answer is "No."

And believe me, I've spent a lot of time on this problem.  There is no actual solution.

However, there are lots of workarounds.  You can pretty much "name your poison".

Here are 3 methods that I know of, presented in my own personal order of preference:

1) The "XGLOB34i.DLL" extender.
2) Passing an array as a function parameter.
3) Using "pointers".  (Not available in all versions of WB)

I'm sure that others will provide the details on these various methods (and perhaps others...)


JTaylor

See if you have the PtrGlobalDefine(variable-name) and PtrGlobal (variable-name) functions.  They have been available for several years so you probably do.

Jim

mpiaser

The easiest solution to what I wanted was to change from DefineFunction to DefineSubroutine.

kdmoyers

Speaking for myself, the PtrGlobal functions are easy and effective.
-Kirby
Code (winbatch) Select
  dbg = @true
  ptrglobaldefine(dbg)

  #definefunction square(x)
      if *ptrglobal(dbg)
        message("x equals",x)
      endif
      return x * x
  #endfunction

  y = square(5)

  message(5,y)
The mind is everything; What you think, you become.

Deana

Yes I would recommend using the PtrGlobal functions. See kdmoyers post for a good code sample.
Deana F.
Technical Support
Wilson WindowWare Inc.

nrr

+1 for the use of pointers.  Be careful changing DefineFunction to DefineSubroutine as you run the risk of inadvertenly changing variable values that you didn't intend to change.
Nick

snowsnowsnow

Quote from: mpiaser on July 10, 2013, 08:45:33 PM
The easiest solution to what I wanted was to change from DefineFunction to DefineSubroutine.

Yes, that's certainly the easiest "one-off" solution - and if it is just one function/subroutine and just one variable involved, then that's probably the best fix.  The question is: Does it scale?  (and: Does it work recursively?)

However, if it is just one variable, then I would like to suggest that you give the array idea a whirl.  That is, make your function like:

#DefineFunction myFun(myarg1,myarg2, A)
; Now use A[0] as if it was a global variable, which, in a sense, it is.
A[0] = "New value"
#EndFunction

; Mainline
A = Arrayize("value"," ") ; I think this is the right syntax; don't have manual handy ATM.
myFun(...,A)
; Now A[0] has a new value.

fhammer

LIMITED use of local environment variables has worked for me. You can create, and set them in a main script, and check them in lower level UDF functions. However, you can't set them externally, and then access them internally, or vice-versa. I also use parameter files to accomplish this.