Looping over menu item creation
-
Hi,
I'm trying to make a context menu that has several items depending on the number of attributes within dictionary, "links_dict". What I have right now works in the sense that it creates items in the submenu with differing titles, but when clicked it always passes the same information. It always takes the information from the last iteration. Is this a bug or is something I have messed up? Any help would be greatly appreciated!
This is the specific lines of interest:
ss = Sketchup.active_model.selection[0] values = ss.attribute_dictionary("link_dict").values for i in Range.new(values.length/2,values.length-1) linkmenu.add_item(%Q{Link to #{values[i]}}) { open_link(values[i-keys.length/2]) } end
A larger chunk if it helps:
if( not file_loaded?("linktofolder2.rb") ) UI.add_context_menu_handler do |menu| if( component_selected ) ss = Sketchup.active_model.selection[0] sd = ss.attribute_dictionary "links_dict", true menu.add_separator linkmenu=menu.add_submenu("PWD; Links") if( ss.attribute_dictionary("link_dict") != nil ) values = ss.attribute_dictionary("link_dict").values for i in Range.new(values.length/2,values.length-1) linkmenu.add_item(%Q{Link to #{values[i]}}) { open_link(values[i-keys.length/2]) } end linkmenu.add_separator end linkmenu.add_item($exStrings.GetString("Add Link")) { add_link } end end end end
-
On the topic of context handlers I recommend you look at this thread I made some while ago: http://forums.sketchucation.com/viewtopic.php?f=180&t=31788
-
When using a for loop, the scope of i is outside the loop.
Try writing the loop like this, where i is has loop scope:
ss = Sketchup.active_model.selection[0] values = ss.attribute_dictionary("link_dict").values Range.new(values.length/2,values.length-1).each do |i| linkmenu.add_item(%Q{Link to #{values[i]}}) { open_link(values[i-keys.length/2]) } end
-
Thank you Jim! That did the trick! So .each method does not hold the iterator variable, but a for loop does in Ruby. Good to know.
Thom, I'm only inspecting the first item that is selected. I'm hoping that doesn't load the entire selection set and cause delays. I'm a relatively novice programmer so I don't really know, but I don't see any studdering with the menu when I have a large selection.
Advertisement