Skip to main content

low_luajit/lua/type/
mod.rs

1use core::{ffi::CStr, fmt::{self, Display}, mem, ptr};
2use crate::{LuaState, ffi};
3
4mod nil;
5mod boolean;
6mod number;
7mod string;
8mod table;
9mod function;
10mod userdata;
11mod thread;
12
13pub use table::*;
14pub use function::*;
15
16/// Possible types for Lua values.
17///
18/// Can be obtained from [`LuaState::type_of`].
19#[repr(i32)]
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum LuaType {
22	/// *(Returned for non-existing elements.)*
23	None = ffi::LUA_TNONE,
24	Nil = ffi::LUA_TNIL,
25	Boolean = ffi::LUA_TBOOLEAN,
26	LightUserdata = ffi::LUA_TLIGHTUSERDATA,
27	Number = ffi::LUA_TNUMBER,
28	String = ffi::LUA_TSTRING,
29	Table = ffi::LUA_TTABLE,
30	Function = ffi::LUA_TFUNCTION,
31	Userdata = ffi::LUA_TUSERDATA,
32	Thread = ffi::LUA_TTHREAD,
33}
34
35impl Display for LuaType {
36	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37		// SAFETY: self.name() always returns simple ASCII strings.
38		f.write_str(unsafe { str::from_utf8_unchecked(self.name().to_bytes()) })
39	}
40}
41
42impl LuaType {
43	/// Returns the name of this type as a string.
44	#[inline]
45	#[must_use]
46	pub fn name(self) -> &'static CStr {
47		// SAFETY: lua_typename does not use the lua_State pointer and always returns a valid nul-terminated string for all LuaType values.
48		unsafe { CStr::from_ptr(ffi::lua_typename(ptr::null_mut(), self as i32)) }
49	}
50}
51
52/// Type related functions.
53///
54/// *[See also the `LuaType` enum](enum.LuaType.html)*.
55impl LuaState {
56	/// Returns the type of the value at the given `index`.
57	///
58	/// Invalid indices will return [`LuaType::None`].
59	#[inline]
60	#[must_use]
61	pub fn type_of(&self, index: i32) -> LuaType {
62		// SAFETY: self.0 is always valid and lua_type always returns a value that can be transmuted to a LuaType.
63		unsafe { mem::transmute(ffi::lua_type(self.0, index)) }
64	}
65
66	/// Checks if there's an element of the given type at the given index `arg_n` and returns it.
67	///
68	/// If the check fails, [`LuaState::type_error`] is called using `arg_n`.
69	///
70	/// # Lua Errors
71	///
72	/// Intentionally errors if the check fails.
73	pub fn check_type(&self, arg_n: i32, r#type: LuaType) {
74		// SAFETY: self.0 is always valid.
75		unsafe { ffi::luaL_checktype(self.0, arg_n, r#type as i32); }
76	}
77}