Reputation: 347
I'm trying to write a while loop that tests whether an input is valid or not and it keeps asking if the user insists on the wrong input. If it is a valid one, the program just goes on. This is where i'm at.
while true
try
selected_row = readline()
selected_row = parse(Int8, selected_row)
break
catch e
if isa(e, LoadError)
@warn "type a valid number between [1,8]"
elseif isa(e, ArgumentError)
@warn "type a valid number between [1,8]"
end
end
end
println("you chose (C|R) ($selected_row)")
The problem is that when the input is correct I get an error.
LoadError: UndefVarError: selected_row not defined
Upvotes: 0
Views: 696
Reputation: 69949
The while
loop creates a new scope. Now the way to fix the issue depends on where you put your code.
If it is inside e.g. a function then use:
local selected_row
before the loop (inside the function body) and things will work.
If your code is in top-level scope write:
global selected_row = parse(Int8, readline())
in your code which will guarantee that a global variable selected_row
will be created.
Having said that I would recommend to write your code as follows:
function get_int8()
while true
selected_row = tryparse(Int8, readline())
isnothing(selected_row) || return selected_row
end
end
selected_row = get_int8()
Upvotes: 2