New sample script - primes.rhai.

This commit is contained in:
Stephen Chung 2020-03-12 23:46:40 +08:00
parent da440a5dff
commit 91317c0d3e
2 changed files with 50 additions and 18 deletions

View File

@ -89,8 +89,8 @@ Example Scripts
There are also a number of examples scripts that showcase Rhai's features, all in the `scripts` folder: There are also a number of examples scripts that showcase Rhai's features, all in the `scripts` folder:
| Script | Description | | Language feature scripts | Description |
| --------------------- | ------------------------------------------------------------- | | ------------------------ | ------------------------------------------------------------- |
| `array.rhai` | arrays in Rhai | | `array.rhai` | arrays in Rhai |
| `assignment.rhai` | variable declarations | | `assignment.rhai` | variable declarations |
| `comments.rhai` | just comments | | `comments.rhai` | just comments |
@ -103,10 +103,14 @@ There are also a number of examples scripts that showcase Rhai's features, all i
| `op1.rhai` | just a simple addition | | `op1.rhai` | just a simple addition |
| `op2.rhai` | simple addition and multiplication | | `op2.rhai` | simple addition and multiplication |
| `op3.rhai` | change evaluation order with parenthesis | | `op3.rhai` | change evaluation order with parenthesis |
| `speed_test.rhai` | a simple program to measure the speed of Rhai's interpreter |
| `string.rhai` | string operations | | `string.rhai` | string operations |
| `while.rhai` | while loop | | `while.rhai` | while loop |
| Example scripts | Description |
| ----------------- | ----------------------------------------------------------------- |
| `speed_test.rhai` | a simple program to measure the speed of Rhai's interpreter |
| `primes.rhai` | use Sieve of Eratosthenes to find all primes smaller than a limit |
To run the scripts, either make a tiny program or use of the `rhai_runner` example: To run the scripts, either make a tiny program or use of the `rhai_runner` example:
```bash ```bash
@ -916,7 +920,7 @@ for x in array {
if x == 42 { break; } if x == 42 { break; }
} }
// The 'range' function allows iterating from first..last-1 // The 'range' function allows iterating from first..last
for x in range(0, 50) { for x in range(0, 50) {
print(x); print(x);
if x == 42 { break; } if x == 42 { break; }

28
scripts/primes.rhai Normal file
View File

@ -0,0 +1,28 @@
// This is a script to calculate prime numbers.
let MAX_NUMBER_TO_CHECK = 10000; // 1229 primes
let prime_mask = [];
prime_mask.pad(MAX_NUMBER_TO_CHECK, true);
prime_mask[0] = false;
prime_mask[1] = false;
let total_primes_found = 0;
for p in range(2, MAX_NUMBER_TO_CHECK) {
if prime_mask[p] {
print(p);
total_primes_found += 1;
let i = 2 * p;
while i < MAX_NUMBER_TO_CHECK {
prime_mask[i] = false;
i += p;
}
}
}
print("Total " + total_primes_found + " primes.");