Add Chunk::name(), Chunk::environment() and Chunk::mode() functions.

They can be used to retrieve existing chunk params.
This commit is contained in:
Alex Orlenko
2025-03-22 00:17:28 +00:00
parent 46e949c184
commit 375028e13f
3 changed files with 37 additions and 2 deletions
+15
View File
@@ -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.
+3 -1
View File
@@ -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(),
+19 -1
View File
@@ -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::<i32>(())?, 987);
Ok(())
}
#[test]
fn test_chunk_path() -> Result<()> {