Making your own native functions
int sample_func( SGS_CTX )
{
char* str;
float q = 1;
SGSFN( "sample_func" );
if( sgs_LoadArgs( "s|f", &str, &q ) )
return 0;
// ... some more code here ...
sgs_PushBool( C, 1 );
return 1; // < number of return values or a negative number on failure
}
- all C functions must have the return type
int
and one sgs_Context*
argument
SGSFN
is used to set the name of the function, the name will be used in:
- error printing
- profiler output generation
sgs_LoadArgs
does type-based argument parsing
- 's' requires a value that can be converted to a string, returns to passed char**
- 'f' requires a value that can be converted to a real value, returns to passed float*
- '|' makes all arguments after it optional (always initialize data passed to those!)
- there are many more options and features for this function, for the whole list, see sgs_LoadArgs
// method #1
sgs_SetGlobalByName( C, "sample_func", sgs_MakeCFunc( sample_func ) );
// method #2
sgs_RegFuncConst funcs[] = { { "sample_func", sample_func } };
sgs_RegFuncConsts( C, funcs, sizeof(funcs) / sizeof(funcs[0]) );
// method #3
sgs_RegFuncConst funcs2[] = { { "sample_func", sample_func }, SGS_RC_END() };
sgs_RegFuncConsts( C, funcs2, -1 );
- Before you can access your functions from scripts, it's necessary to register them.
- The easiest way to register functions is to set them as global variables.
- All of these methods register the same function at the same spot.
- The first method is the easiest (and used internally by the next two) but it expands quickly with function size.
- The second method is for array buffer registration, the third one registers a NULL-terminated list.