Skip to main content

luaur_vm/methods/
lua_exception_what.rs

1use crate::enums::lua_status::lua_Status;
2use crate::macros::lua_errerrmsg::LUA_ERRERRMSG;
3use crate::macros::lua_memerrmsg::LUA_MEMERRMSG;
4use crate::macros::lua_tostring::lua_tostring;
5use crate::records::lua_exception::lua_exception;
6
7#[cfg(any())]
8impl lua_exception {
9    /// C++ `const char* what() const throw() override`
10    pub fn what(&self) -> *const core::ffi::c_char {
11        // LUA_ERRRUN passes error object on the stack
12        if self.status == lua_Status::LUA_ERRRUN as core::ffi::c_int {
13            // SAFETY: lua_tostring is expected to handle invalid stack indices appropriately.
14            if let Some(str) = unsafe { lua_tostring!(self.L, -1) }.as_ref() {
15                return str.as_ptr();
16            }
17        }
18
19        match self.status {
20            x if x == lua_Status::LUA_ERRRUN as core::ffi::c_int => {
21                b"lua_exception: runtime error\0".as_ptr() as *const core::ffi::c_char
22            }
23            x if x == lua_Status::LUA_ERRSYNTAX as core::ffi::c_int => {
24                b"lua_exception: syntax error\0".as_ptr() as *const core::ffi::c_char
25            }
26            x if x == lua_Status::LUA_ERRMEM as core::ffi::c_int => LUA_MEMERRMSG,
27            x if x == lua_Status::LUA_ERRERR as core::ffi::c_int => LUA_ERRERRMSG,
28            _ => {
29                b"lua_exception: unexpected exception status\0".as_ptr() as *const core::ffi::c_char
30            }
31        }
32    }
33}