[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Added `continue` keyword to Lua 5.4 [code review requested].
- From: Sean Conner <sean@...>
- Date: Sat, 18 Mar 2023 04:28:04 -0400
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"
> local ok,ch = pcall(string.char,tonumber(input))
> if not ok and ch then
> print("Failed to parse code:",ch)
> print("Char: "..ch)
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:
io.write "Please input an ASCII code: "
local input = io.read()
if not input:match "^%d+$" then
print "Not a number"
local ok,ch = pcall(string.char,tonumber(input))
if not okay and ch then
print("Failed to parse code: ",ch)
print("Char: " .. ch)
This works across Lua versions 5.1 and higher.