RobertG
RobertG

Reputation: 51

Error message for undefined custom library reference

I am writing a Lua library in C for an embedded system. Is there a way to throw a meaningful error if the script writer tries to call a library function that is not defined in the library?

Right now if (for instance) the script has a spelling mistake, where ez.RS232opn() is called instead of the proper: ez.RS232open() function,

Lua throws a cryptic error of "attempt to call a nil value"

In my library, I would like to throw an error such as "Invalid ez Library function name: RS232opn"

I do understand why the cryptic error is thrown (because the library is actually a Table), but it doesn't mean much to our developers, who are relatively new to Lua.

Forgive me if I missed something, but I searched the Lua documentation and also stackoverflow and Google and couldn't find any clues.

Is this possible?

Upvotes: 1

Views: 62

Answers (2)

Piglet
Piglet

Reputation: 29014

Calling nil values is not allowed in Lua as it does not make any sense.

Lua throws a cryptic error of "attempt to call a nil value"

You usually get a line number, the name and if it is local or global scope. That's all information you need.

it doesn't mean much to our developers, who are relatively new to Lua.

This message should make sense to anyone who read the Lua manual and spent like an hour programming Lua. It is rather self explanatory.

Autocompletion helps to avoid typos in APIs btw.

You could hack something together using metamethods but that's ugly and not necessary. There is only a hand full of error messages. Any Lua developer must know them anyway. So why replace them by another text?

Your

"Invalid ez Library function name: RS232opn"

bears less information than Lua's

input:245 attempt to call a nil value (field 'RS232opn')

btw.

Upvotes: 1

Matthew Taurone
Matthew Taurone

Reputation: 11

What you could do to make it give a customized error for bad function calls is to use regular expressions, called Patterns in Lua. Have it search nil value calls with an ending () and return that they're an invalid function.

Lua.org Patterns page https://www.lua.org/pil/20.2.html

Upvotes: 1

Related Questions