1use std::str::FromStr;
2
3use mlua::prelude::*;
4
5#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
9pub enum LuneStandardGlobal {
10 GTable,
11 Print,
12 Require,
13 Version,
14 Warn,
15}
16
17impl LuneStandardGlobal {
18 pub const ALL: &'static [Self] = &[
22 Self::GTable,
23 Self::Print,
24 Self::Require,
25 Self::Version,
26 Self::Warn,
27 ];
28
29 #[must_use]
33 pub fn name(&self) -> &'static str {
34 match self {
35 Self::GTable => "_G",
36 Self::Print => "print",
37 Self::Require => "require",
38 Self::Version => "_VERSION",
39 Self::Warn => "warn",
40 }
41 }
42
43 #[rustfmt::skip]
51 #[allow(unreachable_patterns)]
52 pub fn create(&self, lua: Lua) -> LuaResult<LuaValue> {
53 let res = match self {
54 Self::GTable => crate::globals::g_table::create(lua),
55 Self::Print => crate::globals::print::create(lua),
56 Self::Require => crate::globals::require::create(lua),
57 Self::Version => crate::globals::version::create(lua),
58 Self::Warn => crate::globals::warn::create(lua),
59 };
60 match res {
61 Ok(v) => Ok(v),
62 Err(e) => Err(e.context(format!(
63 "Failed to create standard global '{}'",
64 self.name()
65 ))),
66 }
67 }
68}
69
70impl FromStr for LuneStandardGlobal {
71 type Err = String;
72 fn from_str(s: &str) -> Result<Self, Self::Err> {
73 let low = s.trim().to_ascii_lowercase();
74 Ok(match low.as_str() {
75 "_g" => Self::GTable,
76 "print" => Self::Print,
77 "require" => Self::Require,
78 "_version" => Self::Version,
79 "warn" => Self::Warn,
80 _ => {
81 return Err(format!(
82 "Unknown standard global '{low}'\nValid globals are: {}",
83 Self::ALL
84 .iter()
85 .map(Self::name)
86 .collect::<Vec<_>>()
87 .join(", ")
88 ));
89 }
90 })
91 }
92}