Dmitry Pashkevich
Dmitry Pashkevich

Reputation: 13536

Lua: no stack trace when calling error() without arguments?

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.

Upvotes: 4

Views: 2051

Answers (1)

Yu Hao
Yu Hao

Reputation: 122403

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.

Upvotes: 7

Related Questions