Simple Argument Value Converter

Started by ., May 24, 2015, 04:54 PM

Previous topic - Next topic

.

This is a simple function to help with the extraction of values from command arg arguments. I've seen many scripters failing to do this properly so here's a simple function to help with that.

Function:
enum ArgType { BOOL = 1, INTEGER = 2, FLOAT = 3, STRING = 4 }

function GetArgValue(arg)
{
    local type = arg.find(".") ? ArgType.FLOAT : ArgType.INTEGER;

    // Eliminate numeric types
    foreach (c in arg)
    {
        //  (c not a 0-9 char) && c != .  && c != +  && c != -
        if ((c < 48 || c > 57) && c != 46 && c != 43 && c != 45)) {
            type = ArgType .STRING;
            break;
        }
    }

    // Are we dealing with an intger?
    if (type == ArgType .INTEGER) {
        try {
            return arg.tointeger();
        } catch(e) {
            // Failed... Dfault to 0
            return 0;
        }
    // Are dealing with a real number?
    } else if (type == ArgType .FLOAT) {
        try {
            return arg.tofloat();
        } catch(e) {
            // Failed... Dfault to 0.0
            return 0.0;
        }
    // Area we toggling something?
    } else if (type == ArgType .STRING) {
        if (arg == "on" || arg == "true" || arg == "enabled") {
            return true;
        } else if (arg == "off" || arg == "false" || arg == "disabled") {
            return false;
        }
    }
    // It's just a string.
    return arg;
}

Example:
print(typeof GetArgValue("123445")); // integer
print(typeof GetArgValue("5432.5643")); // float
print(typeof GetArgValue("true")); // bool
print(typeof GetArgValue("32uh3")); // string

Usage:
local my_val = GetArgValue("244");

// Always check the argument types
if (typeof my_val == "integer")
{
    print(my_val + 6);
}
else
{
    print("Wrong value !");
}

local my_val = GetArgValue("5.53645");

// Always check the argument types
if (typeof my_val == "float")
{
    print(my_val + 0.35434);
}
else
{
    print("Wrong value !");
}

local my_val = GetArgValue("on");

// Always check the argument types
if (typeof my_val == "bool")
{
    if (my_val == true)
        print("Successfully enabled!");
    else
        print("Successfully disabled!");
}
else
{
    print("Wrong value !");
}

local my_val = GetArgValue("236K72"); // Notice that K

// Always check the argument types
if (typeof my_val == "string")
{
    print("You thought this was a number XD " + my_val);
}
else
{
    print("Wrong value !");
}

Happy scripting :P
.