Next: , Previous: , Up: Oct-Files   [Contents][Index]

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 global_varval and global_assign from the current interpreter’s symbol table. Both functions take as first argument a string representing the variable name to be obtained or assigned. The second argument of global_assign is the value to be assigned. An example of the use of these two functions is

#include <octave/oct.h>
#include <octave/interpreter.h>

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

  octave_value retval;

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

  octave::symbol_table& symtab = interp.get_symbol_table ();

  octave_value tmp = symtab.global_varval (s);

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

  symtab.global_assign ("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