Skip to content

Commit

Permalink
Add Table::set_safeenv method (Luau)
Browse files Browse the repository at this point in the history
  • Loading branch information
khvzak committed Dec 4, 2024
1 parent 6f6cda0 commit cacd3dc
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,24 @@ impl Table {
unsafe { ffi::lua_getreadonly(ref_thread, self.0.index) != 0 }
}

/// Controls `safeenv` attribute on the table.
///
/// This a special flag that activates some performance optimizations for environment tables.
/// In particular, it controls:
/// - Optimization of import resolution (cache values of constant keys).
/// - Fast-path for built-in iteration with pairs/ipairs.
/// - Fast-path for some built-in functions (fastcall).
///
/// For `safeenv` environments, monkey patching or modifying values may not work as expected.
///
/// Requires `feature = "luau"`
#[cfg(any(feature = "luau", doc))]
#[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
pub fn set_safeenv(&self, enabled: bool) {
let lua = self.0.lua.lock();
unsafe { ffi::lua_setsafeenv(lua.ref_thread(), self.0.index, enabled as _) };
}

/// Converts this table to a generic C pointer.
///
/// Different tables will give different pointers.
Expand Down
14 changes: 14 additions & 0 deletions tests/luau.rs
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,20 @@ fn test_sandbox() -> Result<()> {
Ok(())
}

#[test]
fn test_sandbox_safeenv() -> Result<()> {
let lua = Lua::new();

lua.sandbox(true)?;
lua.globals().set("state", lua.create_table()?)?;
lua.globals().set_safeenv(false);
lua.load("state.a = 123").exec()?;
let a: i32 = lua.load("state.a = 321; return state.a").eval()?;
assert_eq!(a, 321);

Ok(())
}

#[test]
fn test_sandbox_nolibs() -> Result<()> {
let lua = Lua::new_with(StdLib::NONE, LuaOptions::default()).unwrap();
Expand Down

0 comments on commit cacd3dc

Please sign in to comment.