Skip to content

Comment on If you gaze into nil, nil gazes also into youparent

Comments

This also works really well when combined with the assert function. Any function that returns nil and an error on failure can be wrapped in assert (which is just a normal function that takes a value and a message, and raises an error with the message if the value is nil or false).

If the function returned a value (besides nil or false), then assert merely returns the value. If the function returns nil or false, then assert raises an error, and the error message is used as the error in the assert. For example:

  > = assert(io.open("hello"))
  file (0x8b9f658)
  > = assert(io.open("goodbye"))
  stdin:1: goodbye: No such file or directory
  stack traceback:
    [C]: in function 'assert'
    stdin:1: in main chunk
    [C]: ?
This makes it possible to fail early when you don't need or want to do full error handling, or to use advanced logic if you need to recover from the error - without a try/catch statement. Effectively, it makes exceptions optional.
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.