Metaprogramming: how to use variables from enclosing scope?

A eval statement will always evaluate in the global scope of the module it is located in. Each module has its own separate glocal scope. Your second xDict sits in the global scope of Main whereas the one from the eval is in Testm:

julia> module Testm

              function func()
                         x = rand(10)
                         y = rand(10)

                         x_idx = find(x.< 0.5)
                         y_idx = find(y.> 0.5)

                         for (gg,idx,vals) in ((:xDict,x_idx,x),(:yDict,y_idx,y))
                             @eval begin
                                 ($gg) = Dict(zip($idx,$vals[$idx]))
                             end
                         end
                         return (xDict,yDict)
                     end

              end
Testm

julia> Testm.xDict
ERROR: UndefVarError: xDict not defined

julia> Testm.func() # this creates Testm.xDict
(Dict(7=>0.366333,4=>0.193313,3=>0.341151,5=>0.141716,8=>0.479359),Dict(3=>0.865234,5=>0.722114,8=>0.759312))

julia> Testm.xDict
Dict{Int64,Float64} with 5 entries:
  7 => 0.366333
  4 => 0.193313
  3 => 0.341151
  5 => 0.141716
  8 => 0.479359