PDA

View Full Version : [Tutorial] How to create your own libcod function



Mitch
25th December 2014, 15:09
Since php and kung added real functions we have got two types:
- Functions
- Methods e.g entity setAlive(1)

When you want to run something on an entity you add them to the method list. This way you don't need to specify the entity number as parameter (inside cod).

Method

void gsc_player_getclientstate(int id) { // id is the player's entity number
int info_player = PLAYERBASE(id);
stackPushInt(*(int*)info_player);
}
PLAYERBASE is a macro for 'start address of player' + 'player data size' * entitynumber. The first pointer in this struct points to the client's state (client->state)
With stackPushInt you return the value back to codscript (gsc).

Functions have no parameters. So you need to read them from the stack. (same works for methods)


int id;

if(!stackGetParamInt(0, &id))
{
printf("Param 0 needs to be an int for free_slot\n");
stackPushUndefined();
return;
}

Like used in the function 'free_slot', because you don't have a valid entity.

Before you can use the functions/methods you need to append them to the list in gsc.cpp under scriptFunctions or scriptMethods.


{"free_slot" (1) , gsc_free_slot (2) , 0 (3) },

1. Your function name in codscript (gsc).
2. Your own definition function in libcod.
3. Developer function.

You can use these parameter type functions to retrieve your parameters.


int stackGetParamInt(int param, int *value);
int stackGetParamString(int param, char **value);
int stackGetParamVector(int param, float value[3]);
int stackGetParamFloat(int param, float *value);
int stackGetNumberOfParams();
int stackGetParamType(int param);
char *stackGetParamTypeAsString(int param);
int stackGetParams(char *params, ...);


Return types functions that you can use to return the right type for your function.


int stackPushInt(int ret);
int stackPushVector(float *ret);
int stackPushFloat(float ret);
int stackPushString(char *toPush);
int stackPushEntity(int arg);
int stackPushArray();
int stackPushArrayLast();


Example


void gsc_helloworld() {
char *str;
if ( ! stackGetParams("s", &str)) { // reads the first parameter as string to str.
stackPushUndefined();
return;
} // Edit: you can retrieve multiple params e.g. stackGetParams("ivfs", &int, &vector, &float, &string);

printf(str); // prints your message to the server screen.
stackPushInt(1); // return 1 back to codscript (gsc)
}

{"printhello", gsc_helloworld, 0}, // printhello("Hello World!");


Note: you also need to define your own function in the header file.

You can also look at this commit to see how i added 2 new methods to my libcod repository.
https://github.com/M-itch/libcod/commit/1b7b7d5570895e5895d53fedced4e0e8f88ec9d3