On SketchUp one can request user input using a dialog window created with the UI.Inputbox
method. It is a basic task to ask for the dimension or length of some geometry the script will create afterwards.
Internally SketchUp uses Inches to define geometry. The user will give the answer in his/her localized dimension idiom: '1,5m' for 1.5 Meters. The built in SketchUp method .to_l
converts strings to length. See https://github.com/thomthom/SketchUp-Units-and-Locale-Helper#sketchups-shortcomings for reference.
I'm asking the user for a length as a string from UI.Inputbox
and then converting it to a length value using .to_l
but if the user types an invalid value I don't know how check or how to handle the error.
As my localized length inputs have ',' as the decimal separation (in Portuguese it is 1,5m not 1.5m), I'm not willing to ask for a floating point value.
prompts = ['Length']
defaults = ['1,2']
inputs = UI.inputbox( prompts, defaults ,'Length Input')
inputs[0].to_l
#try inputs[0].to_f
How check the input string or catch .to_l
failure?
I'm asking the user for a length as a string from UI.Inputbox and then converting it to a length value using .to_l
The question is wrong, I mean, it is not a good idea to ask for a string and to try yourself to manage the complexities of localized float values. Don't do it!
Aks for a 'length' and SketchUp will take care of everything for you. Use .m
and the user will be prompted a value in his local/chosen units. The resulting input will be in 'Length - internal units'.
prompts = ['Name', 'Width', 'Height']
defaults = ['My Own Square', 5.m, 2.m]
input = UI.inputbox( prompts, defaults, 'Create Square' )
# User enters Width: 300cm, Height 4
p input
# => ["My Own Square", 118.110236220472, 157.48031496063]
p input.map { |n| n.class }
# => [String, Length, Length]
p input.map { |n| n.to_s }
# => ["My Own Square", "3000mm", "4000mm"]
Source: ThomThom http://www.thomthom.net/thoughts/2012/08/dealing-with-units-in-sketchup/