How do I check type before boxed_cast?


#1

I have a script that returns a value but I do not know the type at compile time. How should I verify the type before boxed_cast to avoid bad cast exceptions?

I would like to use a switch case or if-else pattern if possible.

// pseudo code:
if(typ.is_int){
   // do integer thing
} else if(typ.is_float){
   // do float thing
} else if(typ.is_string){
   // do string thing
}

#2

So I’m assuming you are in c++ at this point and not inside ChaiScript script

Boxed_Value bv = chai.eval("/* something */");

if (bv.is_type(chaiscript::user_type<int>()) { 
  // do int thing
  auto i = chai.boxed_cast<int>(bv);
} else if (bv.is_type(chaiscript::user_type<float>()) {
  // do float thing
  auto f = chai.boxed_cast<float>(bv);
}

-Jason


#3

Perfect. Thanks, @lefticus!