Skip to content

Reinstate str helpers under better name #621

@MightyPork

Description

@MightyPork

Hi, first thanks for maintaining the library.

Regarding a3302af

this just made some work with Value a lot more cumbersome. Calling the Lua string type String is also confusing but that is now part of the API and has to stay. I just rename all the Lua types on import.

I solved the removal of these helpers for now by adding a custom extension trait

pub trait LuaValueExt {
    fn as_str_opt(&self) -> Option<mlua::BorrowedStr<'_>>;
}

impl LuaValueExt for LuaValue {
    fn as_str_opt(&self) -> Option<mlua::BorrowedStr<'_>> {
        self.as_string().and_then(|s| s.to_str().ok())
    }
}

however this feels like something so obvious, it deserves to be included.

I also got tripped by as_f64 not doing a cast if the value is Integer, so I now have custom helpers for that as well, such as

    fn to_f64(&self) -> Result<f64, ConvertError> {
        match &self.0 {
            LuaValue::Nil => Ok(0.0),
            LuaValue::Boolean(v) => Ok(if *v { 1.0 } else { 0.0 }),
            LuaValue::Integer(v) => Ok(*v as f64),
            LuaValue::Number(v) => Ok(*v),
            LuaValue::String(v) => v
                .to_string_lossy()
                .parse::<f64>()
                .map_err(|e| ConvertError::Other(e.to_string().into())),
            LuaValue::LightUserData(_)
            | LuaValue::Table(_)
            | LuaValue::Function(_)
            | LuaValue::Thread(_)
            | LuaValue::UserData(_)
            | LuaValue::Error(_)
            | LuaValue::Other(_) => Err(ConvertError::TypeMismatch),
        }
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions