| Crates.io | stackr-rs |
| lib.rs | stackr-rs |
| version | 0.1.14 |
| created_at | 2025-02-02 18:46:14.046488+00 |
| updated_at | 2025-02-12 16:01:47.297822+00 |
| description | A stack-based interpreter to be embedded in your application. Heavily inspired by Forth. |
| homepage | |
| repository | https://github.com/ericrobolson/stackr-rs |
| max_upload_size | |
| id | 1539793 |
| size | 108,054 |
A stack-based interpreter written in Rust. Heavily inspired by Forth. Useful for embedding a scripting layer in your application.
To add to your project, run:
cargo add stackr-rs
To use the main branch, add this to your Cargo.toml:
[dependencies]
# Reference git repo
stacker-rs = { git = "https://github.com/ericrobolson/stackr-rs.git" }
Run any of the examples with cargo run --example <example-name> or with make example-<example-name>.
1 1 +
: squared
"n -- n^2"
"Squares the top of the stack"
"2 squared"
dup *
;
2 squared
print-stack
"Example of if"
print-stack
drop
1 if
"evaluated when true!"
print-stack
drop
end
"Now we do an example of an else"
print-stack
drop
0 if
"Not ran"
print-stack
drop
else
"else is ran"
print-stack
drop
end
0
begin
print-stack
dup 10 <=
if
drop
"loop finished"
print-stack
break
end
1 +
loop
Note: a loop will never exit unless break is called.
let mut state: u32 = 0;
let mut interpreter = Interpreter::new(state);
interpreter.register_builtin(
"increment-state",
"--",
"Increments the state.",
"increment-state",
|interpreter| {
interpreter.state += 1;
Ok(())
},
);
interpreter.register_builtin(
"get-state",
"-- n",
"Gets the state.",
"get-state",
|interpreter| {
interpreter.push_number(interpreter.state as f32);
Ok(())
},
);
let code = r#"
print-stack
increment-state
print-stack
get-state
print-stack
"#;
interpreter.evaluate(code, None).unwrap();
println!("State after execution: {:?}", interpreter.state);
// Rust code
interpreter.start_repl();
. Noop operation. Used for denoting line breaks in the program.print-stack - Prints the stackdocumentation - Prints all registered words and their documentationdrop, dup, swap, over - Various stack manipulation wordsbegin, loop, break - Loop control wordsif, else, end - If statement control words:, ; - Compilation wordsrepl, repl-end - REPL control wordsThere are more words available, run the documentation word to see all of them or run cargo run --example print_documentation to see all of them.