os2/
os2.rs

1//! Example library that demonstrates the exposing of some Rust functionality to
2//! Lua in an importable library.
3
4use lunka::prelude::*;
5use std::{
6	ffi::c_int,
7	fmt::Write,
8	fs::metadata, time::SystemTime,
9};
10
11unsafe extern "C-unwind" fn l_metadata(l: *mut LuaState) -> c_int {	
12	let lua = unsafe { LuaThread::from_ptr_mut(l) };
13	let path = lua.check_string(1);
14	
15	let meta = match metadata(String::from_utf8_lossy(path).into_owned()) {
16		Ok(meta) => meta,
17		Err(error) => {
18			lua.push_fail();
19			let mut buf = lua.new_buffer();
20			let _ = write!(buf, "{error}");
21			return 2
22		}
23	};
24
25	lua.run_managed(|mut mg| {
26		mg.create_table(0, 1);
27
28		let file_type = meta.file_type();
29		mg.push_string(if file_type.is_file() {
30			"file"
31		} else if file_type.is_dir() {
32			"directory"
33		} else if file_type.is_symlink() {
34			"symlink"
35		} else {
36			"other"
37		}.as_bytes());
38		mg.set_field(-2, c"type");
39
40		mg.push_integer(meta.len() as _);
41		mg.set_field(-2, c"len");
42
43		if let Ok(time) = meta.modified() {
44			if let Ok(time) = time.duration_since(SystemTime::UNIX_EPOCH) {
45				mg.push_number(time.as_secs_f64());
46				mg.set_field(-2, c"modified");
47			}
48		}
49	});
50
51	1
52}
53
54const LIBRARY: LuaLibrary<1> = lua_library! {
55	metadata: l_metadata
56};
57
58#[unsafe(no_mangle)]
59unsafe extern "C-unwind" fn luaopen_os2(l: *mut LuaState) -> c_int {
60	let lua = LuaThread::from_ptr(l);
61	lua.new_lib(&LIBRARY);
62	1
63}