lua-users home
lua-l archive

Re: Added `continue` keyword to Lua 5.4 [code review requested].

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


It was thus said that the Great GoldenKnightFly once stated:
> `continue` is useful if you're working with input checking. For example
> you're checking user input through stdin, you want to check if it's valid
> if not do the input again.
> 
> while true do
> io.write "Please input an ascii code: "
> local input = io.read()
> 
> if not input:match "^%d+$" then
> print "Not a number"
> continue
> end
> 
> local ok,ch = pcall(string.char,tonumber(input))
> if not ok and ch then
> print("Failed to parse code:",ch)
> continue
> end
> 
> print("Char: "..ch)
> break
> end
> end
 I get around the lack of a continue in Lua by using the fact that Lua
supports tail-call optimization. I would recode the above to be:
	function foo()
	 io.write "Please input an ASCII code: "
	 local input = io.read()
	 
	 if not input:match "^%d+$" then
	 print "Not a number"
	 return foo()
	 end
	 local ok,ch = pcall(string.char,tonumber(input))
	 if not okay and ch then
	 print("Failed to parse code: ",ch)
	 return foo()
	 end
	 print("Char: " .. ch)
	end
	foo()
 This works across Lua versions 5.1 and higher.
 -spc

AltStyle によって変換されたページ (->オリジナル) /