title: Groovy scope - how to access script variable in a method
body: <p>I have a question about scoping rules in Groovy. In the following snippet, I have three variables, <code>a</code> has local scope, <code>b</code> has script scope, and <code>c</code> should get script scope as well using the <code>@Field</code> annotation.</p>
  
  <pre><code>#!/usr/bin/groovy
  import groovy.transform.Field;
  
  //println org.codehaus.groovy.runtime.InvokerHelper.getVersion()
  
  def a = 42;
  b = "Tea"
  @Field def c = "Cheese"
  
  void func()
  {
      // println a // MissingPropertyException
      println b // prints "Tea"
      println c // prints "Cheese" with groovy 2.1.2, MissingPropertyException with groovy 1.8.6
  
  }
  
  class Main
  {
      def method()
      {
          // println a // MissingPropertyException
          // println b // MissingPropertyException
          // println c // MissingPropertyException with both 1.8.6. and 2.1.2
      }
  
  }
  
  func();
  new Main().method();
  </code></pre>
  
  <p>I get <code>MissingPropertyException</code>s on the lines indicated with comments. The exceptions on <code>a</code> are expected, as that variable has local scope. But I would expect <code>b</code> to be accessible inside <code>method()</code> - it isn't.
  <code>@Field</code> doesn't do anything in groovy 1.8.6, although after upgrading it works, so I guess that is an old bug. Nevertheless, <code>c</code> is inaccessible inside <code>method()</code> with either version.</p>
  
  <p>So my questions are:</p>
  
  <ol>
  <li>Why can't I access a variable annotated with <code>@Field</code> inside
  <code>method()</code>? </li>
  <li>How can I refer to a script variable inside <code>method()</code>?</li>
  </ol>