[Tutorial] y_ini simplified
#1

This is a much simpler method of using y_ini that many people don't know. This is also my attempt at writing a simpler tutorial than normal.

File

Assume you want your file to look like this:

Code:
[player_data]
health = 57.0
weapon = 12
ammo = 9
name = Y_Less
"player_data" is the "tag", and everything else are "key/value pairs", i.e. "key = value".

Writing

Writing to this type of file is easy:

Code:
SavePlayer(playerid)
{
    // Get the player's name.
    new name[MAX_PLAYER_NAME];
    GetPlayerName(playerid, name, sizeof (name));
    // Get their save location.
    new fileName[MAX_PLAYER_NAME + 10];
    format(fileName, sizeof (fileName), "users\\%s.ini", name);
    // Open the file.
    new INI:ini = INI_Open(fileName);
    // Set the tag.
    INI_SetTag(ini, "player_data");
    // Write out all the bits of data.
    new Float:health;
    GetPlayerHealth(playerid, health);
    INI_WriteFloat(ini, "health", health); // Get their health somehow.
    INI_WriteFloat(ini, "weapon", GetPlayerWeapon(playerid));
    INI_WriteFloat(ini, "ammo", GetPlayerAmmo(playerid));
    INI_WriteFloat(ini, "name", name);
    // Close the file.
    INI_Close(ini);
}
Now all the data is correctly written to a player's file. Note that this is NOT the best way to write a user system - y_users is a VASTLY better option.

Reading

Reading these files is also easy, if you use inline functions:

Code:
LoadPlayer(playerid)
{
    new name[MAX_PLAYER_NAME];
    GetPlayerName(playerid, name, sizeof (name));
    // Declare some variables to load data in to.
    // YSI 4.0 can use "new" here instead of "static".
    static weapon, ammo;
    // This "function" is called once for every entry in the INI file.
    inline Load(string:name[], string:value[])
    {
        if (!strcmp(name, "health")) SetPlayerHealth(playerid, floatstr(value));
        else if (!strcmp(name, "weapon")) weapon = strval(value);
        else if (!strcmp(name, "ammo")) ammo = strval(value);
    }
    // Get their load location.
    new fileName[MAX_PLAYER_NAME + 10];
    format(fileName, sizeof (fileName), "users\\%s.ini", name);
    // Parse the INI file, tell it to use our inline function for reading the data.
    INI_ParseFile(fileName, using inline Load);
    // The data is loaded in to our local variables, use it.
    GivePlayerWeapon(playerid, weapon, ammo);
}
Note that:

Code:
else if (!strcmp(name, "weapon")) weapon = strval(value);
else if (!strcmp(name, "ammo")) ammo = strval(value);
Can also be written as:

Code:
else INI_Int("weapon", weapon);
else INI_Int("ammo", ammo);
Yes, two "else"s in a row - "INI_Int" includes an "if" (this is a bad design, but is how it is).
Reply
#2

The code is not readable, i like this but I can't understand the code in the form that you've posted .
Reply
#3

Fixed newlines
Reply


Forum Jump:


Users browsing this thread: 2 Guest(s)