Implement ToLua for a particular HashMap type #271
-
Hello! Thanks for all the work on this library. What I'm trying to accomplish is for a user to specify a table in a file that will get deserialized using #[derive(Deserialize, Debug)]
pub enum RecordValidType {
String(String),
Number(f64),
Table(HashMap<String, RecordValidType>),
} And it's being used in another deserializing struct like this: #[derive(Deserialize, Debug)]
pub struct LuaFnInput {
pub tag: String,
pub timestamp: String,
pub record: HashMap<String, RecordValidType>,
} I tried to implement the // error handling removed for brevity, just assume everything is perfect hooray
impl<'lua> ToLua<'lua> for RecordValidType {
fn to_lua(self, lua: &'lua mlua::Lua) -> mlua::Result<Value<'lua>> {
match self {
String => return Ok(self.to_lua(lua).unwrap()),
Number => return Ok(self.to_lua(lua).unwrap()),
Table => {
// In a theoretical world where this works
let record: HashMap<String, RecordValidType> = HashMap::from(self);
let table = lua.create_table().unwrap();
for row in record.iter() {
table.set(*row.0, *row.1);
}
return Ok(table);
}
}
}
} However this is pretty clearly wrong, and I'm not sure how to pull it off. Is this something that is possible? Am I completely off-base and there's a better way to accomplish this? Thank you in advance! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Probably you don't even need let lua_val = lua.to_value(&RecordValidType::Number(1.0))?; You just need to import |
Beta Was this translation helpful? Give feedback.
Probably you don't even need
ToLua
implementation forRecordValidType
.mlua (with
serialize
feature flag) support integration with serde. If you addderive(Serialize)
toRecordValidType
then should be able to automatically convert it to Lua.Eg:
You just need to import
LuaSerdeExt
trait.