tmail/amstd/gconst.rb

#
# gconst.rb
#
#     Copyright (c) 1999 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
#
#
# usage:
#
#   global_const :$GLOBAL_VAR, val
#   $GLOBAL_VAR = 'another value'    # NameError
#
#   global_const :$wrong_name, val   # NameError
#

require 'amstd/to_s'
require 'amstd/must'


def global_const( name, val )
  name = _name2str( name )

  unless /\A\$[A-Z][\w\d]*\z/o === name then
    raise ArgumentError, "wrong name '#{name}' for global constant"
  end

  if eval name then
    raise NameError, "global variable #{name} is already initialized"
  end

  eval "#{name} = val"
  trace_var( name ) do
    raise NameError, "global constant '#{name}' is already initialized"
  end
end


if $0 == __FILE__ then
  global_const :$E, 'this is $E'      # set new global constant
  puts $E
  begin
    $E = 'wrong value for $E'          # name error
  rescue
    puts $!
  end
  
  begin
    global_const :$a, 'wrong name'  # wrong name
  rescue
    puts $!
  end
end