[][src]Module gameshell::predicates

Contains pre-built predicates for use outside this library for creating command specifications.

Writing a custom predicate

use gameshell::{types::Type, Evaluate, Evaluator};
use gameshell::cmdmat::{Decider, Decision, SVec};

// This is the general decider type to use
pub type SomeDec = Option<&'static Decider<Type, String>>;

// This is your decider that you will use when registering a handler
pub const I32_NUMBER_ABOVE_123: SomeDec = Some(&Decider {
    description: "<i32-over-123>",
    decider: i32_number_above_123,
});

fn i32_number_above_123(input: &[&str], out: &mut SVec<Type>) -> Decision<String> {
    // Check if input is non-empty
    if input.is_empty() {
        return Decision::Deny("No input received".into());
    }

    // Ensure string contains no whitespaces
    for i in input[0].chars() {
        if i.is_whitespace() {
            return Decision::Deny(input[0].into());
        }
    }

    // Parse string to i32
    let number = input[0].parse::<i32>();
    let number = match number {
        Ok(number) => number,
        Err(err) => return Decision::Deny(format!["{:?}", err]),
    };

    // Ensure number is >123
    if !(number > 123) {
        return Decision::Deny("Number is not >123".into());
    }

    // All checks passed, push the value to the output
    out.push(Type::I32(number));

    // Tell the GameShell machinery that we have consumed 1 argument
    Decision::Accept(1)
}

fn handler(_: &mut (), args: &[Type]) -> Result<String, String> {
    if let [Type::I32(number)] = args {
        println!["The number {} is definitely greater than 123", number];
        Ok("We can return whatever we want to here".into())
    } else {
        panic!["Wrong arguments"];
    }
}

let mut eval = Evaluator::new(());
eval.register((&[("my-command", I32_NUMBER_ABOVE_123)], handler));
eval.interpret_single("my-command 124").unwrap().unwrap();
assert_eq![Err("Expected <i32-over-123>. Decider: Number is not >123".into()), eval.interpret_single("my-command -9").unwrap()];

Constants

ANY_ATOM

Accepts a single string which does not contain whitespace

ANY_BASE64

Accepts any base64 string

ANY_BOOL

Accepts a single boolean

ANY_F32

Accepts a single f32

ANY_I32

Accepts a single i32

ANY_STRING

Accepts a single string

ANY_U8

Accepts a single u8

IGNORE_ALL

Ignores all arguments

MANY_I32

Accepts 1 or more i32s

MANY_STRING

Accepts 1 or more strings

TWO_STRINGS

Accepts two strings

Type Definitions

SomeDec

Decider type alias