$ versus @
-
I personally change all the @'s to $'s before I use a Ruby within SU ,
I like the idea that $'s retains the value, I have just entering into a dialog box
while @'s reverts back to the original value that a particular Ruby came with.what are your thoughts?
-
Hi,
I also use globals but it is a bad habit, unless you give your $'s a name that has no chance to be used by another script (creates conflict). But it is a lazy way of retaining values for your dialog boxes for instance, so user get the last values used.
One can avoid globals when using classes and methods, classes variables (@@) and objects variables (@). -
never, ever use globals in Ruby - beside name clash conflicts (as Didier said) you will have a lot of problems debugging it when someone else (your script or other) changes and you don't know why. of course you can use trace variable and see the caller stack, but why shoot yourself in the foot ?
-
@unknownuser said:
never, ever use globals in Ruby
I admit I have done it.
Simply because I don't know how not to.
A simple tutorial with example code would be of tremendous help.By the way I've seen the use of double @@. What's that for?
-
I think everyone use it
Pixero: give me an example when you really need a global and I will make an example on not using it
@ - instance variable
@@ - class variablesee http://railstips.org/2006/11/18/class-and-instance-variables-in-ruby
-
@unknownuser said:
Pixero: give me an example when you really need a global and I will make an example on not using it
All these globals in the script below for example:
(By the way if I would need a variable that was remembered even after leaving the plugin and re entering. Should that be a global?
Like if I set a $currentFrame variable and wanted it to be recalled later when using the script again? Hope I make myself clear.)# Name; jsMoveTool # Author; Jan Sandstrom www.pixero.com # Description; Moves a selection with the arrow keys. # Usage; 1. Select a object or group of objects. # 2. Select the JS MoveTool and enter a distance in the VCB. Press Return/Enter. # 3. Now move with arrow keys. # 4. Use Alt + Up/Down to move in Z axis. # 5. You can enter a new distance at any time. # # Version 1.1 # Added; # 6. Press Ctrl (Apple Key on Mac) for distance * 0.1 # 6. Press Shift for distance * 10 require 'sketchup.rb' class JS_MoveTool def activate # This sets the label for the VCB Sketchup;;set_status_text "Distance", SB_VCB_LABEL end model = Sketchup.active_model entities = model.active_entities ss = model.selection if RUBY_PLATFORM == "i386-mswin32" then # Win XP $leftArrow = 37 # Arrow Left Key $upArrow = 38 # Arrow Up Key $rightArrow = 39 # Arrow Right Key $downArrow = 40 # Arrow Down Key $altKey = 18 # Alt Key $shiftKey = 16 # Shift Key $controlKey = 17 # Control Key elsif RUBY_PLATFORM == "powerpc-darwin" then # Mac OSX $leftArrow = 63234 # Arrow Left Key $upArrow = 63232 # Arrow Up Key $rightArrow = 63235 # Arrow Right Key $downArrow = 63233 # Arrow Down Key $altKey = 524288 # Alt/Option Key $shiftKey = 131072 # Shift Key $controlKey = 1048576 # Command (Apple) Key end #if def onUserText (text, view) # The user may type in something that we can't parse as a length # so we set up some exception handling to trap that begin $value = text.to_l rescue # Error parsing the text UI.beep puts "Cannot convert #{text} to a Length" $value = nil Sketchup;;set_status_text "", SB_VCB_VALUE end return if !$value Sketchup;;set_status_text $value.to_s, SB_VCB_VALUE def onKeyDown(key, repeat, flags, view) # puts key # For debug - finding the right keycodes if (key == $altKey) $altDown = true; end #if if (key == $shiftKey) $shiftDown = true; end #if if (key == $controlKey) $controlDown = true; end #if @distance = $value Sketchup.active_model.selection.each {|e| # X axis if (key == $rightArrow) # Right dist = Geom;;Point3d.new [@distance, 0, 0]; end#if if ($controlDown == true && key == $rightArrow) # Right * 0.1 @distance = @distance * 0.1; dist = Geom;;Point3d.new [@distance, 0, 0]; end#if if ($shiftDown == true && key == $rightArrow) # Right * 10 @distance = @distance * 10; dist = Geom;;Point3d.new [@distance, 0, 0]; end#if if (key == $leftArrow) # Left dist = Geom;;Point3d.new [-@distance, 0, 0]; end#if if ($controlDown == true && key == $leftArrow) # Left * 0.1 @distance = @distance * 0.1; dist = Geom;;Point3d.new [-@distance, 0, 0]; end#if if ($shiftDown == true && key == $leftArrow) # Left * 10 @distance = @distance * 10; dist = Geom;;Point3d.new [-@distance, 0, 0]; end #if # Y axis if (key == $upArrow) # Up dist = Geom;;Point3d.new [0, @distance, 0]; end #if if ($controlDown == true && key == $upArrow && $altDown == false) # Up * 0.1 @distance = @distance * 0.1; dist = Geom;;Point3d.new [0, @distance, 0]; end #if if ($shiftDown == true && key == $upArrow && $altDown == false) # Up * 10 @distance = @distance * 10; dist = Geom;;Point3d.new [0, @distance, 0]; end #if if (key == $downArrow) # Down dist = Geom;;Point3d.new [0, -@distance, 0]; end #if if ($controlDown == true && key == $downArrow && $altDown == false) # Down * 0.1 @distance = @distance * 0.1; dist = Geom;;Point3d.new [0, -@distance, 0]; end #if if ($shiftDown == true && key == $downArrow && $altDown == false) # Down * 10 @distance = @distance * 10; dist = Geom;;Point3d.new [0, -@distance, 0]; end #if # Z axis if ($altDown == true && key == $upArrow) # Alt + Up dist = Geom;;Point3d.new [0, 0, @distance]; end #if if ($controlDown == true && $altDown == true && key == $upArrow) # Alt + Up * 0.1 @distance = @distance * 0.1; dist = Geom;;Point3d.new [0, 0, @distance]; end #if if ($shiftDown == true && $altDown == true && key == $upArrow) # Alt + Up * 10 @distance = @distance * 10; dist = Geom;;Point3d.new [0, 0, @distance]; end #if if ($altDown == true && key == $downArrow) # Alt + Down dist = Geom;;Point3d.new [0, 0, -@distance]; end #if if ($controlDown == true && $altDown == true && key == $downArrow) # Alt + Down * 0.1 @distance = @distance * 0.1; dist = Geom;;Point3d.new [0, 0, -@distance]; end #if if ($shiftDown == true && $altDown == true && key == $downArrow) # Alt + Down * 10 @distance = @distance * 10; dist = Geom;;Point3d.new [0, 0, -@distance]; end #if # Now move it! tr = Geom;;Transformation.new (dist); Sketchup.active_model.entities.transform_entities(tr, e); } #each end #onKeyDown end #onUserText def onKeyUp(key, repeat, flags, view) if (key == $altKey) $altDown = false; end #if if (key == $shiftKey) $shiftDown = false; end #if if (key == $controlKey) $controlDown = false; end #if end #def end # end of jsMoveTool if( not file_loaded?("jsMoveTool.rb") ) plugins_menu = UI.menu("Plugins") plugins_menu.add_item("JS MoveTool") { Sketchup.active_model.select_tool JS_MoveTool.new } end
-
- replace all arrow codes with constants - e.g. $leftarrow -> LEFTARROW
- replace rest of globals with class variables - e.g. $value -> @@value
tested and it works (retains distance between calls of tool)
-
The original question was about why bother using anything but globals.
Given at the end of the day its just bytes in memory, why do all these pesky computer scientists keep harping on about using locals and scoping stuff?
Well, at the end of the day, it is just memory somewhere. But as programs became more and more complex the opportunities to shoot yourself in the foot and introduce bugs into the logic of your programs became more and more common.
So rather than have to make correctness assertions about a million lines of code, computer scientists started breaking down large programs into small self-contained pieces of a tens of lines of code that were guaranteed to have no 'side effects' outside themselves. Having shown the individual functions were correct, they could then move up and start making correctness assertions about groups of functions and so on. Its called a 'hierarchy of confidence' and without it you'd simply never be able to get big software projects out the door.
So, ensuring that variables are only accessible and changeable by certain well known bits of your program is just to make your life easier.
Ditto laying out your (Ruby) code with rigid rules about formatting/indentation. It just helps spot errors. Ditto naming variables that give a hint about the meaning of the variable. Ditto naming functions to reflect what they actually do and not having 'hidden magic' they do on the side..
So, if you want to use globals, and put all your Ruby code on a single line with no spaces. Go knock yourself out - you are free to do so. Its just making things hard for yourself - but each to his/her own.
Thinking about who needs to be able to access variables is a good exercise before you even approach a keyboard to ensure you've thought things through.
Having said all that, if you're writing a 10 line program and want to use globals because you've got a few minutes to bang some code out - don't have a guilt trip about - we've all done it.
The flip side is that those who have worked on multi-million line projects adopt these ways or working for a good reason and not just for the hell of it.
And lastly, for compiled code in C++/C# etc, using locals and avoiding globals will often results in the compiler generating faster code for you because it can rely on just the small set of local variables changing not anything and everything.
Phew,
Adam -
@unknownuser said:
- replace all arrow codes with constants - e.g. $leftarrow -> LEFTARROW
- replace rest of globals with class variables - e.g. $value -> @@value
tested and it works (retains distance between calls of tool)
So, should we be creating new instances of a Tool each time, or referencing the already existing instance? (Instance level variables will also continue to exists for the life of the session, if you don't instantiate a new class every time the tool is activated.)
-
I'd suggest always re-instance a Tool unless there is a compelling reason to make it persist.
As a general rule, releasing resources as soon as possible is a GoodThing, and secondly - and probably more importantly in a Ruby context, to ensure you don't carry references to Ruby objects and therefore stop garbage collection happening - worse still carry stale references to objects that have subsequently been deleted which tends to make SU jump into the azure blue sea of unallocated heap store and commit hare-kiri.
Adam
-
@didier bur said:
Hi,
But it is a lazy way of retaining values for your dialog boxes for instance, so user get the last values used.
One can avoid globals when using classes and methods, classes variables (@@) and objects variables (@).I'm sorry but I cant let this topic die just yet. I have carefully reread all the
comments. Does this quote offer a solution to retaining values in Dialog Boxes? -
For a dialog's default values that you want keeping from session to session within a particular model, I write them as attributes to the model itself: when the dialog initialises it looks for their values, if they are not there it takes defaults - otherwise you have them saved on a model by model basis... For an example see my TextTag.rb.
.
-
So, there you have it - three solutions that avoid globals:
- Sketchup.read_default and Sketchup.write_default (persistent across SketchUp sessions and models)
- Attributes (persistent within a given model, between sessions)
- Class variables (@@variable) (persistent only within a SketchUp session)
-
For persistent data for Dialog Boxes, you should use Sketchup.write_default and Sketchup.read_default. The keys and values are stored in the registry (Windows) and the plist (Mac).
Todd
-
@rickw said:
So, there you have it - three solutions that avoid globals:
- Sketchup.read_default and Sketchup.write_default (persistent across SketchUp sessions and models)
- Attributes (persistent within a given model, between sessions)
- Class variables (@@variable) (persistent only within a SketchUp session)
Thanks everyone; I took a quick look at TIG's, TextTag.rb. It appears to take a little bit more understanding of Ruby then just simply banging out a mass replacement of @ to $ or vise versa. Nevertheless I will try to implement
these attributes on an exisitng Ruby of mine. -
Hi all !
Just one question : How can you do when you have that :
class ToolsObsTest < Sketchup;;ToolsObserver def onActiveToolChanged (tools_object, toolname, toolid) [b]@t[/b] = toolid end end
and this variable @t is used here :
module def [b]@t[/b] end end
So the variable is not used inside the first class section, but inside the instance of a module section ???
To find variable, I use $....How can I preserve variable value ????
-
Just define your Observer class in the scope of your Module
module Foo class ToolsObsTest < Sketchup;;ToolsObserver def onActiveToolChanged (tools_object, toolname, toolid) @t = toolid end end end instance = Foo;;ToolsObsTest.new
-
Hi AdamB !
Thak you for your answer...I tried it but it didn't work for me... @toolID (variable name in the code) always returns nil....
here is the real "tree" of the code (including your advice)module Toto class ToolsObsTest < Sketchup;;ToolsObserver def onActiveToolChanged (tools_object, toolname, toolid) @toolID = toolid end end ### def self.act model.tools.add_observer(Toto;;ToolsObsTest.new) end ### def self.obs(id) @toolID end end
Do you know why your method doesn't work ?
Thank you ! -
Matt,
The two @toolid are different. One is a Class instance variable, the other a Module variable.
If you want to track the toolid in module Toto, then use a method to set its value, which you can call from the class.
Note that normally, you might use a Module variable, with @@, (since module instance variables do not really have real application)def Toto.set_toolid(toolid) @@toolid = toolid end def Toto.get_toolid() @@toolid end
Fredo
-
Hello Fredo6 !
Thank you for your answer ! It works great ! get_toolid & set_toolid are perfect !
Just one thing, @@variable doesn't work. Just @variable...Thank you Fredo !
Advertisement