Skip to content

Commit

Permalink
Add FnPtr to get_literal_value.
Browse files Browse the repository at this point in the history
  • Loading branch information
schungx committed May 10, 2024
1 parent e6caf3a commit 031a5a9
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 3 deletions.
3 changes: 2 additions & 1 deletion src/api/custom_syntax.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,9 +131,10 @@ impl Expression<'_> {
/// Returns [`None`] also if the constant is not of the specified type.
#[inline]
#[must_use]
pub fn get_literal_value<T: Variant>(&self) -> Option<T> {
pub fn get_literal_value<T: Variant + Clone>(&self) -> Option<T> {
// Coded this way in order to maximally leverage potentials for dead-code removal.
match self.0 {
Expr::DynamicConstant(x, ..) => x.clone().try_cast::<T>(),
Expr::IntegerConstant(x, ..) => reify! { *x => Option<T> },

#[cfg(not(feature = "no_float"))]
Expand Down
4 changes: 2 additions & 2 deletions tests/custom_syntax.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#![cfg(not(feature = "no_custom_syntax"))]

use rhai::{Dynamic, Engine, EvalAltResult, ImmutableString, LexError, ParseErrorType, Position, Scope, INT};
use rhai::{Dynamic, Engine, EvalAltResult, FnPtr, ImmutableString, LexError, ParseErrorType, Position, Scope, INT};

#[test]
fn test_custom_syntax() {
Expand Down Expand Up @@ -278,7 +278,7 @@ fn test_custom_syntax_func() {
let mut engine = Engine::new();

engine
.register_custom_syntax(["hello", "$func$"], false, |context, inputs| context.eval_expression_tree(&inputs[0]))
.register_custom_syntax(["hello", "$func$"], false, |_, inputs| Ok(inputs[0].get_literal_value::<FnPtr>().unwrap().into()))
.unwrap();

assert_eq!(engine.eval::<INT>("call(hello |x| { x + 1 }, 41)").unwrap(), 42);
Expand Down

0 comments on commit 031a5a9

Please sign in to comment.