summaryrefslogtreecommitdiff
path: root/src/lua/mod.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/lua/mod.rs')
-rw-r--r--src/lua/mod.rs85
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
+ )))
}
}