LoginLogin

Passing a variable into a function using a reference string.

Root / Programming Questions / [.]

MZ952Created:
The simple argument I seek works a little like thisโ€”
  • Check if variable exists using CHKVAR
  • If variable name exists, pass its reference into function
I'm pretty sure what I'm trying to do is comparable to pointing and referencing in C++ (only took a month's worth of CPP in my engineering class, so not too sure). Say I have a set of variables A0,A1,A2, and I need to pass one of them into a function based on the value of N. I don't want to create multiple functions with each having one of the 3 different variables to work on. I want to use a single instance of the function, and so I need to pass a "variable" variable into it. I think I've seen something like this done before, but it's too vague for my memory. Some syntax along the lines of VAR("A"+STR$(N)) (to suit the above example).
DEF FUNC A
REM Do something with A
END
N=0
R=CHKVAR("A"+STR$(N))
IF(R)THEN
 FUNC VAR("A"+STR$(N))
ENDIF
I'm just really at a loss of how this can be done.

EDIT2: There are many ways to do this:
'Passing the value (read only)
FUNC1 VAR("A")
FUNC1 A 'same

DEF FUNC1 V
 PRINT V
 V=3 'DOES NOT WORK
END

'passing the name (only works with global variables)
FUNC2 "A"

DEF FUNC2 V$
 PRINT VAR(V$)
 VAR(V$)=3
END

'input and output (works with anything)
FUNC3 VAR("A") OUT VAR("A")
FUNC3 A OUT A 'same
VAR("A")=FUNC3(VAR("A")) 'same
A=FUNC3(A) 'same

DEF FUNC3 V_IN OUT V
 V=V_IN 'get value
 PRINT V
 V=3
END

'using arrays to cheat:
'(arrays are passed as reference type always, so changing an array inside a function will change the real array, unlike with number variables)
DIM A[1]
FUNC4 VAR("A")
FUNC4 A 'same

DEF FUNC4 V[]
 PRINT V[0]
 V[0]=3
END

Though if you just have 3 different variables it might be better to use an array or even an IF/ELSEIF block.
Well, this was just a water-downed example. Huh. I just did a little testing, and I found it to work. Thanks! On another related question, though, can I create a variable using another string variable or literal (or some other method?) The program in question would work a little better if it could create variables with the reference name given by another variable.

You can't create new variables, so if you need to store more data you'll have to use arrays.