diff options
| author | Nathan Reiner <nathan@nathanreiner.xyz> | 2024-07-26 10:32:55 +0200 |
|---|---|---|
| committer | Nathan Reiner <nathan@nathanreiner.xyz> | 2024-07-26 10:32:55 +0200 |
| commit | 6ca07d6af8a338e76817d06c6c6c6f13e64fba9c (patch) | |
| tree | 32680f0942da8c45af8425ebc20330f5456a9213 /src/lua/mod.rs | |
| parent | 8b7c56df1940d2ac6e3ece3385464009e46382fa (diff) | |
add neosheetrc support
Diffstat (limited to 'src/lua/mod.rs')
| -rw-r--r-- | src/lua/mod.rs | 85 |
1 files changed, 38 insertions, 47 deletions
diff --git a/src/lua/mod.rs b/src/lua/mod.rs index 5d45ee9..0ddcd7f 100644 --- a/src/lua/mod.rs +++ b/src/lua/mod.rs @@ -1,10 +1,34 @@ -use std::time::{SystemTime, UNIX_EPOCH}; +use std::{ + path::Path, + sync::{Mutex, MutexGuard}, +}; +use lazy_static::lazy_static; use mlua::prelude::*; -use crate::sheet::{cell::CellRef, register::Register}; +use crate::sheet::cell::CellRef; pub mod iobuffer; +pub mod runtime; + +lazy_static! { + static ref LUA: Mutex<Lua> = { + let lock = Mutex::new(Lua::new()); + + { + let lua = lock.lock().unwrap(); + + let print_binding = lua.create_function(print).unwrap(); + lua.globals().set("print", print_binding).unwrap(); + + runtime::math(&lua).unwrap(); + runtime::neosheet(&lua).unwrap(); + runtime::package(&lua).unwrap(); + } + + lock + }; +} fn print(_: &Lua, args: LuaMultiValue) -> LuaResult<()> { let mut writer = iobuffer::iobuffer().write().unwrap(); @@ -28,53 +52,20 @@ fn print(_: &Lua, args: LuaMultiValue) -> LuaResult<()> { Ok(()) } -pub fn new_instance() -> LuaResult<Lua> { - let lua = Lua::new(); - - let print_binding = lua.create_function(print)?; - lua.globals().set("print", print_binding)?; - - { - let math = lua.globals().get::<_, LuaTable>("math"); - let randomseed = math.unwrap().get::<_, LuaFunction>("randomseed").unwrap(); - - let seed = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_millis(); - randomseed.call::<_, ()>(seed).unwrap(); - } - - let neosheet = lua.create_table()?; - - let register = Register; - neosheet.set("sheets", register)?; - - lua.globals().set("neosheet", neosheet)?; - - Ok(lua) +pub fn get() -> MutexGuard<'static, Lua> { + LUA.lock().unwrap() } -#[cfg(test)] -mod test { - use mlua::Function; - - use super::new_instance; +pub fn source(path: &str) -> LuaResult<()> { + let path = Path::new(path); - #[test] - fn function_eval() { - let lua = new_instance().unwrap(); - let func: Function = lua - .load( - r#" - function(a, b, c) - return a + b * c - end - "#, - ) - .eval() - .unwrap(); - eprintln!("{}", func.call::<_, String>((1, 2, 3, 4)).unwrap()); - assert!(false); + if path.exists() && path.is_file() { + get().load(path).exec()?; + Ok(()) + } else { + Err(LuaError::runtime(format!( + "could not source {:?} (file not found)", + path + ))) } } |