From 9a8da93145e24666e1676120d791135d4e4eb2e5 Mon Sep 17 00:00:00 2001 From: Stephen Chung Date: Sat, 17 Apr 2021 18:10:57 +0800 Subject: [PATCH] Delay creation of global module until actually needed. --- src/engine.rs | 10 +++++++++- src/fn_call.rs | 4 ---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/engine.rs b/src/engine.rs index 8196d18d..1eaca300 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -2517,7 +2517,15 @@ impl Engine { let (var_name, _alias): (Cow<'_, str>, _) = if state.is_global() { #[cfg(not(feature = "no_function"))] if entry_type == AccessMode::ReadOnly { - let global = mods.get_mut(mods.find(KEYWORD_GLOBAL).unwrap()).unwrap(); + let index = if let Some(index) = mods.find(KEYWORD_GLOBAL) { + index + } else { + // Create automatic global module + mods.push(crate::engine::KEYWORD_GLOBAL, Module::new()); + mods.len() - 1 + }; + + let global = mods.get_mut(index).unwrap(); let global = Shared::get_mut(global).unwrap(); global.set_var(name.clone(), value.clone()); global.build_index(); diff --git a/src/fn_call.rs b/src/fn_call.rs index 3840c587..2a5c904c 100644 --- a/src/fn_call.rs +++ b/src/fn_call.rs @@ -826,10 +826,6 @@ impl Engine { lib: &[&Module], level: usize, ) -> RhaiResult { - // Create the global module - #[cfg(not(feature = "no_function"))] - mods.push(crate::engine::KEYWORD_GLOBAL, Module::new()); - self.eval_stmt_block(scope, mods, state, lib, &mut None, statements, false, level) .or_else(|err| match *err { EvalAltResult::Return(out, _) => Ok(out),