4

In Lua, calling the standard error() function with a message argument outputs the provided error message and also prints stack trace, e.g. executing the following code:

print("hello")
error("oops!")
print("world")

would result in the following output:

$ lua test.lua
hello
lua: test.lua:2: oops!
stack traceback:
    [C]: in function 'error'
    test.lua:2: in main chunk
    [C]: ?

However, calling error() without arguments seems to make Lua die silently without printing stack trace. Executing this code:

print("hello")
error()    // no arguments provided
print("world")

would result in this output:

$ lua test2.lua
hello

The documentation doesn't say anything about omitting the first message argument:

error (message [, level])

Terminates the last protected function called and returns message as the error message. Function error never returns. Usually, error adds some information about the error position at the beginning of the message. The level argument specifies how to get the error position. With level 1 (the default), the error position is where the error function was called. Level 2 points the error to where the function that called error was called; and so on. Passing a level 0 avoids the addition of error position information to the message.

I'm wondering if this is intended behavior or no? IMO it would make sense to still print stack trace (and maybe output some default text e.g. error) even if no message is provided, because that's how the assert() function works.

1 Answer 1

7

The documentation doesn't say anything about omitting the first message argument:

Yes, it does, error() has a prototype like this:

error (message [, level])

Notice that only the arguments inside [] is optional, in this case level, otherwise the arguments are mandatory, in this case, message.

Comparing with the prototype of assert():

assert (v [, message]) 

As you can see, message in assert() is optional.

3
  • 2
    @DmitryPashkevich It doesn't really work because error expects a message argument. Otherwise it probably depends on the implementation of the function and might cause other errors. If you really want to just pass an empty string error("") Aug 2, 2013 at 8:54
  • 1
    @DmitryPashkevich Because Lua is OK with incompatible numbers of arguments, in that case, error will receive the first parameter as nil.
    – Yu Hao
    Aug 2, 2013 at 8:56
  • So the error() function probably fails with an internal error and doesn't finish properly... that makes sense, thanks! Aug 2, 2013 at 9:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.