Add set_var to context

Closes #2
main
trivernis 1 year ago
parent 2edbf12a42
commit 1e7c71095d
Signed by: Trivernis
GPG Key ID: DFFFCC2C7A02DB45

@ -5,7 +5,7 @@ pub use builder::*;
pub use command_group_config::CommandGroupConfig;
use nu_protocol::{
ast::{Block, Call},
engine::{EngineState, Stack},
engine::{EngineState, Stack, StateWorkingSet},
PipelineData, Span,
};
@ -13,7 +13,7 @@ use crate::{
argument::IntoArgument,
error::{CrateError, CrateResult},
utils::parse_nu_script,
NewEmpty,
IntoValue, NewEmpty,
};
/// Represents the evaluation context of nu scripts and commands
@ -125,4 +125,21 @@ impl Context {
Ok(())
}
/// Adds a variable to the context
pub fn add_var<S: ToString, V: IntoValue>(&mut self, name: S, value: V) -> CrateResult<()> {
let mut working_set = StateWorkingSet::new(&self.engine_state);
let var_id = working_set.add_variable(
name.to_string().into_bytes(),
Span::empty(),
nu_protocol::Type::Any,
false,
);
self.stack.add_var(var_id, value.into_value());
let delta = working_set.render();
self.engine_state.merge_delta(delta)?;
Ok(())
}
}

@ -24,6 +24,15 @@ fn it_returns_variables() {
assert_eq!(val.as_string().unwrap(), String::from("world"))
}
#[test]
fn it_accepts_variables() {
let mut ctx = get_context();
ctx.add_var("hello", "world").unwrap();
let val = ctx.get_var("hello").expect("No variable returned");
assert_eq!(val.as_string().unwrap(), String::from("world"))
}
#[derive(RustyValue)]
struct TestArg {
foo: String,

Loading…
Cancel
Save