summaryrefslogtreecommitdiff
path: root/src/lua/mod.rs
blob: 0ddcd7faf5232644cc236aa5df07794866a42985 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
use std::{
    path::Path,
    sync::{Mutex, MutexGuard},
};

use lazy_static::lazy_static;
use mlua::prelude::*;

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();

    for (i, arg) in args.iter().enumerate() {
        if let Some(ud) = arg.as_userdata() {
            if ud.is::<CellRef>() {
                writer.write(ud.borrow::<CellRef>().unwrap().value().to_string());
            } else {
                writer.write(format!("{:#?}", ud));
            }
        } else {
            writer.write(format!("{:#?}", arg));
        }

        if i < args.len() - 1 {
            writer.write(", ");
        }
    }
    writer.writeln("");
    Ok(())
}

pub fn get() -> MutexGuard<'static, Lua> {
    LUA.lock().unwrap()
}

pub fn source(path: &str) -> LuaResult<()> {
    let path = Path::new(path);

    if path.exists() && path.is_file() {
        get().load(path).exec()?;
        Ok(())
    } else {
        Err(LuaError::runtime(format!(
            "could not source {:?} (file not found)",
            path
        )))
    }
}