Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add FnPtr to get_literal_value. #872

Merged
merged 1 commit into from
May 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading