Beginner questions. [get std::map inside of a std::vector and magic methods]


#1

Hello.
Can I receive on ChaiScript values of a std::vector <std::map <std::string, uint16_t >>?
I’ve been trying to do something similar to this:

C++:

std::vector<std::map<std::string, uint16_t>> getBox(uint8_t value) {  
     std::vector<std::map<std::string, uint16_t>> Box;

     for (uint8_t i = 0; i < value; i++) {
	if (isItem(i)) {
		std::map<std::string, uint16_t> Attributes = {
			{ "index", Item[i].index },
			{ "type" , Item[i].type },
			{ "count", Item[i].count }
		};

		Box.push_back(Attributes);
	  }
     }

     return Box;
}

ChaiScript:

auto ItemList = obj.box()

for (auto i = 0; i < ItemList.size() - 1; ++i) {
     if (ItemList[i]["level"] == 1) {
          func(ItemList[i]);
     }
}

And obviously it doesn’t work…

Also I wonder if I can deploy magic methods get/set to a variable or function with the same name, like this:

ChaiScript:

//I know it's wrong, it's just an example for better understanding

var obj = __magicmethod(                     
    [get, (){ return get_obj(); }],
    [set, (v){ set_obj(v); }]
);

def myClass::item() { return _item; } // get
def myClass::item(value) { _item = value; } // set

I’m now beginning to learn about embedding code in my application and I don’t have extensive knowledge in C ++ language, let alone in ChaiScript.
Forgive my english, I’m using translator.

Thank you.


#2

The first question can work exactly like you want, but by default ChaiScript only understands std::vector<BoxedValue> (called Vector inside of ChaiScript) and std::map<std::string, Boxed_Value> (called Map inside of ChaiScript).

You will have to tell ChaiScript how to work with these types you want to use:

chai.add(chaiscript::bootstrap::standard_library::vector_type<std::vector<std::map<std::string, uint16_t>>("VectorOfMapOfInt"));
chai.add(chaiscript::bootstrap::standard_library::map_type<std::map<std::string, uint16_t>("MapOfInt"));

See also here for some other examples: https://github.com/ChaiScript/ChaiScript/blob/develop/cheatsheet.md#using-stl

I’m not sure I’m understanding what you want to do with the second question. ChaiScript does support “method_missing” if that’s what you want.

It has it built in for built in objects, so this is a complete valid example.

class myClass {
  def myClass() { }
};

var obj = myClass();
obj.item = 4

Or you can specify the member name:

class myClass {
  var item;
  def myClass() { }
};

var obj = myClass();
obj.item = 4

or you can do it like you show:

class myClass {
  var _item;
  def myClass() { }
  def item() { return _item; }
  def item(value) { _item = value; }
};

var obj = myClass();
obj.item() = 4; // this would work
obj.item(4); // or this
obj.item = 4; // or even this, because () is not necessary on a method call in ChaiScript