C Functions
A C function has the type int CFunc( sgs_Context* )
. It receives the context that called it and must return the number of return values pushed on stack.
Conventions
There are no forced courses of action beyond this point. However, to simplify development, some conventions were established and are used throughout the standard library and are suggested to follow.
General structure
- the usage of SGS_CTX in argument list is suggested to enable the use of certain macros that assume the availability of
sgs_Context* C
- there are no restrictions on function names, however it helps to mark the scripting engine functions with a common prefix and if they wrap a native function, including the name of the wrapped function is suggested
Argument loading
- prefer using sgs_LoadArgs, followed by sgs_LoadArgsExt, followed by the sgs_Parse***/sgs_Is***/sgs_ItemType(Ext)/... functions together with ArgError function family for error handling
Error handling
- it is preferred to do most of it at the beginning, before custom allocations (VM stack doesn't count here), where it is possible to just
return sgs_Msg( C, SGS_WARNING, "Error message" )
- SGS_WARNING is for non-fatal errors, SGS_ERROR is for errors that make it impossible to continue (severe, undoubted logical errors fall into this category)
- on error, functions should return nothing or null
A typical function
int sgsfunc_sample( SGS_CTX ) { sgs_Int num; char* str; char* buf; sgs_SizeVal bufsize; if( !sgs_LoadArgs( C, "ism", &num, &str, &buf, &bufsize ) ) return 0; if( bufsize == 0 ) return sgs_Msg( C, SGS_WARNING, "buffer cannot be empty" ); // sgs_Msg always returns 0 // .. do something with the passed arguments .. // anything can be returned .. // .. but in this case, we want to say .. // .. that the action was successful sgs_PushBool( C, 1 ); return 1; }