lua-users home
lua-l archive

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


On 2018-09-14 22:24, Joseph Manning wrote:
My question is about the use of 'return' to halt the script.

I think it *should* be valid, since the script contents forms a chunk,
which is treated as an (anonymous) function, and the 'return' from
inside this function should be fine.  Am I correct?

Yes.

The only difference is that a plain `return` will always exit with an exit code of zero in the vanilla Lua interpreter, but it is common to signal errors with a non-zero exit code. Thus, `os.exit( false )` (or `os.exit( false, true )` if you rely on __gc cleanup) is usually better.

A common idiom is something like

  function die( reason )
    io.stderr:write( arg[0], ": ", reason, "\n" )
    os.exit( false, true )
  end

with which you can

  die "two parameters expected"

(This also sends the error message to stderr, so that if the output is piped into another program, the user will still get to see it and it won't confuse the other program.)

-- nobody