Skip to content

Overloadable Index #263

@lupan

Description

@lupan

This is 2 different things which I have used many times in lua for more powerful dynamic object handling, simply the act of overloading what happens when you use either object.whatever and object["whatever"], I have used this many times to write dynamic message systems via internal templates to create fully runtime handled objects, this is horrible to use in rust due to fact its a lot of function calls, but in scripting langs it is quite simple and beautiful, for example:

struct template { //for generating the msg at runtime
    name: String,
    fields: Vec<(String, TypeEnum)> //name and default value
}
struct dynamic_msg {
    template: Arc<template>,
    fields: HashMap<String, TypeEnum> //name of field and inner value (this is cloned from template)
}
impl dynamic_msg {
  fn set_dynamic_field(&mut self, name: &str, new_value: TypeEnum) -> Result<()> {
      self.fields[name] = new_value; //missed out the checks for simplicity sake
      Ok(())
  }
fn get_dynamic_field(&self, name: &str) -> Result<&TypeEnum> {
      let val = self.fields.get(name); //missed out the checks for simplicity sake
      Ok(val)
  }
fn get_dynamic_field_mut(&mut self, name: &str) -> Result<&mut TypeEnum> {
      let val = self.fields.get_mut(name); //missed out the checks for simplicity sake
      Ok(val)
  }
}

in lua I usually override the index function on the userdata and make it simply run the set and get dynamic field functions, allowing me in lua to write this:

msg = create_msg("name")
msg.field = "potato"
etc etc
return msg

I realize this is possible using Object but that comes with 2 issues for me, one it doesn't handle if I try to access or create a field which isn't part of the msg, and it has to be parsed from and into the Object type, as for the dynamic struct system which is great, it requires the scripter to write the structs themselves.

p.s. this example above is purposely simple and far from what the optimized and expanded version would look like.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions