Accessing script variables from ruby console

I’m new to ruby and the Sketchup API. I’ve noticed some discussion of the problems of writing scripts that have no explicit module, and whose binding is TOPLEVEL_BINDING. IIUC, said binding is associated (and I’m not sure exactly this works) with the Object class.

If I write a such a script, and that script includes local variables, those variables are not visible in the console after I “load” the script. I have read that including a second argument of “true” with your “load” call will wrap the script in an anonymous module, preventing contamination of the namespace of the TOPLEVEL_BINDING with any constants from the script. In that case, the anonymous module is deleted on completion of the load.

My question is, what is the scope of local variables defined in a script which does NOT have the optional “wrap” argument? Do those variables disappear into the GC after completion of the script load process?

top-level local variables have “file” scope - that is they only exist in the file which they are defined.

If you need to, you can print out all the local variables at the end of the file:

local_variables.each do |sym|
  puts "#{sym} = #{eval(sym.to_s)})"
end

Yes, they are not propagated into the global ObjectSpace.

But, beware. Class variables, instance variables and constants are propagated.


If you are doing testing. You may wish to use Aerulius’ Ruby Console+. It allows you to set a cutsom module binding for console evaluation. (Just type the qualified name of your module into the “binding box” in the middle of the toolbar. It defaults to “global”.)
http://extensions.sketchup.com/en/content/ruby-console

So for example, if I am tesing a plugin defined in a Widget sub-module, wrapped in a Dan toplevel author module, I would load the file, then type Dan::Widget into the binding box.