mlua/tests/memory.rs

61 lines
1.4 KiB
Rust
Raw Normal View History

2019-09-28 10:23:17 -04:00
use std::sync::Arc;
2019-10-14 17:21:30 -04:00
use mlua::{Lua, Result, UserData};
2019-09-28 10:23:17 -04:00
#[test]
fn test_gc_control() -> Result<()> {
2019-10-14 17:21:30 -04:00
let lua = Lua::new();
let globals = lua.globals();
2019-09-28 10:23:17 -04:00
2019-11-29 08:26:30 -05:00
#[cfg(any(feature = "lua53", feature = "lua52"))]
2019-10-14 17:21:30 -04:00
{
assert!(lua.gc_is_running());
lua.gc_stop();
assert!(!lua.gc_is_running());
lua.gc_restart();
assert!(lua.gc_is_running());
}
2019-09-28 10:23:17 -04:00
struct MyUserdata(Arc<()>);
impl UserData for MyUserdata {}
let rc = Arc::new(());
globals.set("userdata", lua.create_userdata(MyUserdata(rc.clone()))?)?;
globals.raw_remove("userdata")?;
2019-09-28 10:23:17 -04:00
assert_eq!(Arc::strong_count(&rc), 2);
lua.gc_collect()?;
lua.gc_collect()?;
assert_eq!(Arc::strong_count(&rc), 1);
Ok(())
}
2019-11-29 08:26:30 -05:00
#[cfg(any(feature = "lua53", feature = "lua52"))]
2019-09-28 10:23:17 -04:00
#[test]
fn test_gc_error() {
2019-10-14 17:21:30 -04:00
use mlua::Error;
let lua = Lua::new();
2019-09-28 10:23:17 -04:00
match lua
.load(
r#"
val = nil
table = {}
setmetatable(table, {
__gc = function()
error("gcwascalled")
end
})
table = nil
collectgarbage("collect")
2019-09-28 10:23:17 -04:00
"#,
)
.exec()
{
Err(Error::GarbageCollectorError(_)) => {}
Err(e) => panic!("__gc error did not result in correct error, instead: {}", e),
Ok(()) => panic!("__gc error did not result in error"),
}
}