luna/src/lua.rs

35 lines
1.0 KiB
Rust

use std::{cell::RefCell, rc::Rc};
use mlua::{DeserializeOptions, Function, Lua, LuaSerdeExt, Value};
pub fn try_eval(lua: &Lua, src: &str) -> mlua::Result<(String, String)> {
lua.scope(|s| {
let output = Rc::new(RefCell::new(String::new()));
let output_ = Rc::clone(&output);
let print = s.create_function(move |lua, x: Value| {
let s = lua
.globals()
.get::<_, Function>("tostring")?
.call::<_, String>(x)?;
let mut output = output_.borrow_mut();
output.push_str(&s);
output.push('\n');
Ok(())
})?;
lua.globals().set("print", print)?;
let res = lua.from_value_with::<serde_json::Value>(
lua.load(src).eval()?,
DeserializeOptions::new()
.deny_unsupported_types(false)
.deny_recursive_tables(false),
)?;
let res = serde_json::to_string_pretty(&res).unwrap();
Ok((output.take(), res))
})
}