diff --git a/src/chunk.rs b/src/chunk.rs index 089f4b8..a973d27 100644 --- a/src/chunk.rs +++ b/src/chunk.rs @@ -307,6 +307,11 @@ impl Compiler { } impl Chunk<'_> { + /// Returns the name of this chunk. + pub fn name(&self) -> &str { + &self.name + } + /// Sets the name of this chunk, which results in more informative error traces. /// /// Possible name prefixes: @@ -318,6 +323,11 @@ impl Chunk<'_> { self } + /// Returns the environment of this chunk. + pub fn environment(&self) -> Option<&Table> { + self.env.as_ref().ok()?.as_ref() + } + /// Sets the environment of the loaded chunk to the given value. /// /// In Lua >=5.2 main chunks always have exactly one upvalue, and this upvalue is used as the @@ -334,6 +344,11 @@ impl Chunk<'_> { self } + /// Returns the mode (auto-detected by default) of this chunk. + pub fn mode(&self) -> ChunkMode { + self.detect_mode() + } + /// Sets whether the chunk is text or binary (autodetected by default). /// /// Be aware, Lua does not check the consistency of the code inside binary chunks. diff --git a/src/state.rs b/src/state.rs index 756e4ac..5224e60 100644 --- a/src/state.rs +++ b/src/state.rs @@ -1011,7 +1011,9 @@ impl Lua { ) -> Chunk<'a> { Chunk { lua: self.weak(), - name: chunk.name().unwrap_or_else(|| location.to_string()), + name: chunk + .name() + .unwrap_or_else(|| format!("@{}:{}", location.file(), location.line())), env: chunk.environment(self), mode: chunk.mode(), source: chunk.source(), diff --git a/tests/chunk.rs b/tests/chunk.rs index 16df553..47ec038 100644 --- a/tests/chunk.rs +++ b/tests/chunk.rs @@ -1,6 +1,24 @@ use std::{fs, io}; -use mlua::{Chunk, Lua, Result}; +use mlua::{Chunk, ChunkMode, Lua, Result}; + +#[test] +fn test_chunk_methods() -> Result<()> { + let lua = Lua::new(); + + #[cfg(unix)] + assert!(lua.load("return 123").name().starts_with("@tests/chunk.rs")); + let chunk2 = lua.load("return 123").set_name("@new_name"); + assert_eq!(chunk2.name(), "@new_name"); + + let env = lua.create_table_from([("a", 987)])?; + let chunk3 = lua.load("return a").set_environment(env.clone()); + assert_eq!(chunk3.environment().unwrap(), &env); + assert_eq!(chunk3.mode(), ChunkMode::Text); + assert_eq!(chunk3.call::(())?, 987); + + Ok(()) +} #[test] fn test_chunk_path() -> Result<()> {