hello/
hello.rs

1//! "Hello, world!" example running in Lua.
2
3use core::ffi::c_int;
4use lunka::prelude::*;
5
6unsafe extern "C-unwind" fn l_main(l: *mut LuaState) -> c_int {
7	let lua = unsafe { LuaThread::from_ptr_mut(l) };
8	lua.run_managed(move |mut mg| mg.open_libs());
9
10	let is_ok = lua.load_string(
11		r#"print("Hello, world!")"#,
12		c"=<embedded>"
13	).is_ok();
14	if !is_ok {
15		let error = {
16			lua.to_string(-1)
17				.and_then(move |bytes| core::str::from_utf8(bytes).ok())
18				.unwrap_or("<message is not UTF-8>")
19		};
20		eprintln!("couldn't load example Lua code:\n\t{error}");
21		lua.push_boolean(false);
22		return 1
23	}
24
25	let is_ok = lua.run_managed(move |mut mg| unsafe { mg.pcall(0, 0, 0).is_ok() });
26	if !is_ok {
27		let error = {
28			lua.to_string(-1)
29				.and_then(move |bytes| core::str::from_utf8(bytes).ok())
30				.unwrap_or("<message is not UTF-8>")
31		};
32		eprintln!("couldn't run example Lua code:\n\t{error}");
33		lua.push_boolean(false);
34		return 1
35	}
36
37	lua.push_boolean(true);
38	1
39}
40
41fn main() {
42	let mut lua = Lua::new();
43
44	let did_run_ok = lua.run_managed(move |mut mg| {
45		mg.push_c_function(l_main);
46		if unsafe { mg.pcall(0, 1, 0).is_ok() } {
47			mg.to_boolean(-1)
48		} else {
49			false
50		}
51	});
52	if !did_run_ok {
53		panic!("couldn't run \"Hello, world!\" example for some reason");
54	}
55}