[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Modifying global variables from within functions
From: |
John W. Eaton |
Subject: |
Modifying global variables from within functions |
Date: |
Tue, 13 Nov 2001 15:03:28 -0600 |
On 13-Nov-2001, Roberto Hernandez <address@hidden> wrote:
| I am trying to modify a global variable directly from within a function.
| The solution I found is somewhat complicated for what I want. I was
| wondering if there's a better way to do it.
|
| Here's the situation. The function "foo" has to accept a global variable
| name and a value and assign the value to the variable.
|
| For example this function:
|
| ------------------------------
| function foo(varName, newValue)
| eval(["global ", varName]);
|
| if isnumeric(newValue)
| eval([varName, " = " , num2str(newValue), ";"])
| else
| eval([varName, " = \"" , newValue, "\";"])
| endif
| endfunction
| ------------------------------
|
| So I would call it this way:
|
| ------------------------------
| octave:1> global a
| octave:2> foo("a", 5)
| ans = 5
| octave:3> foo("a", "hello")
| ans = hello
| ------------------------------
|
| The previous example works fine. But if I want to do more complex
| operations inside the function "foo", then having to use "eval" and
| building lots of strings becomes annoying. It's easy to make mistakes
| and pretty bad for debugging.
|
| The question is: Is there a better way to do this?
How about
function foo (__n__, __v__)
eval (sprintf ("global %s; %s = __v__;", __n__, __n__));
endfunction
??
jwe
-------------------------------------------------------------
Octave is freely available under the terms of the GNU GPL.
Octave's home on the web: http://www.octave.org
How to fund new projects: http://www.octave.org/funding.html
Subscription information: http://www.octave.org/archive.html
-------------------------------------------------------------