From cfa2aa50b554255d4e4982cc06b8333f555bfc1c Mon Sep 17 00:00:00 2001 From: AsynchronousMatrix Date: Mon, 24 Jul 2023 20:09:18 +0100 Subject: [PATCH] feature: implement 'luau' library for Lune' --- src/lune/builtins/luau.rs | 58 +++++++++++++++++++++++++++++++++++++++ src/lune/builtins/mod.rs | 1 + src/lune/importer/mod.rs | 1 + 3 files changed, 60 insertions(+) create mode 100644 src/lune/builtins/luau.rs diff --git a/src/lune/builtins/luau.rs b/src/lune/builtins/luau.rs new file mode 100644 index 0000000..1515c2d --- /dev/null +++ b/src/lune/builtins/luau.rs @@ -0,0 +1,58 @@ +use mlua::prelude::*; +use mlua::Compiler as LuaCompiler; + +use crate::lua::table::TableBuilder; + +pub fn create(lua: &'static Lua) -> LuaResult { + TableBuilder::new(lua)? + .with_function("compile", compile_source)? + .with_function("load", load_source)? + .build_readonly() +} + +fn compile_source<'a>( + lua: &'static Lua, + (source, options): (LuaString<'a>, Option>), +) -> LuaResult> { + let mut optimization_level = 1; + let mut coverage_level = 0; + let mut debug_level = 1; + + if let Some(options) = options { + optimization_level = options.raw_get("optimizationLevel")?; + coverage_level = options.raw_get("coverageLevel")?; + debug_level = options.raw_get("debugLevel")?; + } + + let source_bytecode_bytes = LuaCompiler::default() + .set_optimization_level(optimization_level) + .set_coverage_level(coverage_level) + .set_debug_level(debug_level) + .compile(source); + + match lua.create_string(source_bytecode_bytes) { + Ok(lua_string) => Ok(lua_string), + Err(exception) => Err(LuaError::RuntimeError(exception.to_string())), + } +} + +fn load_source<'a>( + lua: &'static Lua, + (source, options): (LuaString<'a>, Option>), +) -> LuaResult> { + let mut lua_debug_name = "".to_string(); + + if let Some(options) = options { + lua_debug_name = options.raw_get("debugName")? + } + + let lua_object = lua + .load(source.to_str()?.trim_start()) + .set_name(lua_debug_name) + .into_function(); + + match lua_object { + Ok(lua_function) => Ok(lua_function), + Err(exception) => Err(LuaError::RuntimeError(exception.to_string())), + } +} diff --git a/src/lune/builtins/mod.rs b/src/lune/builtins/mod.rs index 20b13a4..46aefbe 100644 --- a/src/lune/builtins/mod.rs +++ b/src/lune/builtins/mod.rs @@ -1,4 +1,5 @@ pub mod fs; +pub mod luau; pub mod net; pub mod process; pub mod serde; diff --git a/src/lune/importer/mod.rs b/src/lune/importer/mod.rs index c0658d1..de3cdf6 100644 --- a/src/lune/importer/mod.rs +++ b/src/lune/importer/mod.rs @@ -14,6 +14,7 @@ pub fn create(lua: &'static Lua, args: Vec) -> LuaResult<()> { ("serde", builtins::serde::create(lua)?), ("stdio", builtins::stdio::create(lua)?), ("task", builtins::task::create(lua)?), + ("luau", builtins::luau::create(lua)?), #[cfg(feature = "roblox")] ("roblox", builtins::roblox::create(lua)?), ];