I work on Lua electronic device simulation plug in.
I want to make it good in design and usability, as most probably a lot of users are far from IT and debugging.
Users describe device in Lua and plug in translates it via Lua C API.
Users may misspell function names, variables types and arguments order.
Good manual helps but application shouldn't crash or provide bad described errors. I didn't find any "best practices" and want to ask experience users as I'm quite new to Lua.
Arguments' order and type
At the moment Lua functions are declared like this:
typedef struct lua_bind_func
{
int32_t ( *lua_c_api ) ( lua_State* );
const char* lua_func_name;
} lua_bind_func;
And then
{.lua_func_name="state_to_string", .lua_c_api=&lua_state_to_string},
In order to check that argument order and types are passed correct:
Create macros:
#define STRING (&lua_isstring)
#define INT (&lua_isinteger)
#define USER (&lua_islightuserdata)
Add an array to the list:
int ( *args[16] ) ( lua_State*, int index );
Change function list:
{.lua_func_name="set_callback", .lua_c_api=&lua_set_callback, .args={INT, INT}}
Argument list checker:
static void
SAFE_EXECUTE ( lua_State* L, void* curfunc )
{
int argnum = lua_gettop ( L );
for ( int i=0; lua_c_api_list[i].lua_func_name; i++ )
{
if ( curfunc == lua_c_api_list[i].lua_c_api )
{
for ( int argcount=0; lua_c_api_list[i].args[argcount]; argcount++ )
{
if ( argnum < argcount+1 )
{
IDSIMMODEL* model = ( IDSIMMODEL* ) lua_get_model_obj ( L );
print_error ( model, "Too few arguments passed to the function \"%s\"", lua_c_api_list[i].lua_func_name );
}
else if ( !lua_c_api_list[i].args[argcount] ( L, argcount+1 ) )
{
IDSIMMODEL* model = ( IDSIMMODEL* ) lua_get_model_obj ( L );
print_error ( model, "Argument %d is of wrong type", argcount+1 );
}
}
}
}
}
Then I can check argument order, their types and can create corresponding error message with mini help:
SAFE_EXECUTE ( L, &lua_set_callback );
The code doesn't handle extra arguments, but it's easy to add.
Question: Is it OK scenario or may be there is a better one?
Misspelled function names
For example I have the following code:
set_callback(time + 100 * MSEC, PC_EVENT)
set_calback(time + 200 * MSEC, PC_EVENT)
set_callback(time + 333 * MSEC, PC_EVENT)
The second one is misspelled and after this part no code is executed.
I can't understand how to catch a call to undefined function in C in order to raise adequate error.
Other pitfalls
Maybe there are more possible pitfalls I don't know about?