W3cubDocs

/Octave

A.1.7 Accessing Global Variables in Oct-Files

Global variables allow variables in the global scope to be accessed. Global variables can be accessed within oct-files by using the support functions get_global_value and set_global_value. get_global_value takes two arguments, the first is a string representing the variable name to obtain. The second argument is a boolean argument specifying what to do if no global variable of the desired name is found. An example of the use of these two functions is

#include <octave/oct.h>

DEFUN_DLD (globaldemo, args, , "Global Demo")
{
  if (args.length () != 1)
    print_usage ();

  octave_value retval;

  std::string s = args(0).string_value ();

  octave_value tmp = get_global_value (s, true);

  if (tmp.is_defined ())
    retval = tmp;
  else
    retval = "Global variable not found";

  set_global_value ("a", 42.0);

  return retval;
}

An example of its use is

global a b
b = 10;
globaldemo ("b")
⇒ 10
globaldemo ("c")
⇒ "Global variable not found"
num2str (a)
⇒ 42

© 1996–2018 John W. Eaton
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions.
https://octave.org/doc/interpreter/Accessing-Global-Variables-in-Oct_002dFiles.html