title: How and when are variables referenced in Delphi's anonymous methods captured?
body: <p>This was prompted by <a href="https://stackoverflow.com/questions/5153486/how-to-compare-tfunc-tproc-containing-function-procedure-of-object">How to compare TFunc/TProc containing function/procedure of object?</a>, specifically by David's comment to Barry's question. Since I don't have a Blog to post this to I'm going to ask this question here, and answer it.</p>
  
  <p><strong>Question</strong>: When and how are variables referenced in Delphi's anonymous methods captured?</p>
  
  <p>Example:</p>
  
  <pre><code>procedure ProcedureThatUsesAnonymousMethods;
  var V: string;
      F1: TFunc&lt;string&gt;;
      F2: TFunc&lt;string&gt;;
  begin
    F1 := function: string
          begin
            Result := V; // references local variable
          end
    V := '1';
    F2 := function: string
          begin
            Result := V;
          end
   V := '2';
   ShowMessage(F1);
   ShowMessage(F2);
  end;
  </code></pre>
  
  <p>Both <code>ShowMessage</code> are going to show <code>2</code>. Why? How does <code>V</code> get captured and when?</p>