From bed5256e2e554a03a60bd228576a153432a700b8 Mon Sep 17 00:00:00 2001 From: Stephen Chung Date: Mon, 7 Jun 2021 20:15:06 +0800 Subject: [PATCH] Add new example scripts. --- scripts/function_decl3.rhai | 4 ++-- scripts/function_decl4.rhai | 12 ++++++++++++ scripts/if2.rhai | 10 ++++++++++ scripts/switch.rhai | 11 +++++++++++ 4 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 scripts/function_decl4.rhai create mode 100644 scripts/if2.rhai create mode 100644 scripts/switch.rhai diff --git a/scripts/function_decl3.rhai b/scripts/function_decl3.rhai index 872b9745..c1c84631 100644 --- a/scripts/function_decl3.rhai +++ b/scripts/function_decl3.rhai @@ -6,6 +6,6 @@ fn f(a, b, c, d, e, f) { a - b * c - d * e - f + global::KEY } -print("f() call should be 42:"); +let result = f(100, 5, 2, 9, 6, 32); -print(f(100, 5, 2, 9, 6, 32)); +print(`result should be 42: ${result}`); diff --git a/scripts/function_decl4.rhai b/scripts/function_decl4.rhai new file mode 100644 index 00000000..a09ed3fc --- /dev/null +++ b/scripts/function_decl4.rhai @@ -0,0 +1,12 @@ +// This script defines a function that acts as a method + +// Use 'this' to refer to the object of a method call +fn action(x, y) { + this = this.abs() + x * y; // 'this' can be modified +} + +let obj = -40; + +obj.action(1, 2); // call 'action' as method + +print(`obj should now be 42: ${obj}`); diff --git a/scripts/if2.rhai b/scripts/if2.rhai new file mode 100644 index 00000000..a42bb337 --- /dev/null +++ b/scripts/if2.rhai @@ -0,0 +1,10 @@ +let a = 42; +let b = 123; + +let x = if a <= b { // if-expression + b - a +} else { + a - b +} * 10; + +print(`x should be 810: ${x}`); diff --git a/scripts/switch.rhai b/scripts/switch.rhai new file mode 100644 index 00000000..a252fa66 --- /dev/null +++ b/scripts/switch.rhai @@ -0,0 +1,11 @@ +let arr = [42, 123.456, "hello", true, 'x', 999, 1]; + +for item in arr { + switch item { + 42 => print("The Answer!"), + 123.456 => print(`Floating point... ${item}`), + "hello" => print(`${item} world!`), + 999 => print(`A number: ${item}`), + _ => print(`Something else: <${item}>`) + } +}