如何访问脚本中定义的类型的成员?

How do I access members of a type defined in a script?

我正在尝试从我在脚本中定义的类型访问 C++ 文件成员。问题是 Boxed_Value::get_attr 总是 return 空值。

这是我的 C++ 文件:

#include <chaiscript/chaiscript.hpp>
#include <iostream>

int main()
{
  chaiscript::ChaiScript chai;
  chaiscript::Boxed_Value test_value = chai.eval_file("script.chai");
  chaiscript::Boxed_Value number = test_value.get_attr("number");
  std::cout << chaiscript::boxed_cast<int>(number) << std::endl;
}

script.chai:

class MyType
{
  attr number
  def MyType
  {
    this.number = 30
  }
}
MyType()

我希望它打印 30,但它却抛出了 bad_boxed_cast 异常。在我的投资过程中,我发现 number.is_null() 是正确的。 我明明做错了,却找不到我的错误。
或者也许它不打算以这种方式使用?

不是答案,但我添加了一堆调试;

  chaiscript::Boxed_Value test_value = chai.eval_file("script.chai");
  auto info = test_value.get_type_info();
  printf("%d\n", info.is_const());
  printf("%d\n", info.is_reference());
  printf("%d\n", info.is_void());
  printf("%d\n", info.is_arithmetic());
  printf("%d\n", info.is_undef());
  printf("%d\n", info.is_pointer());
  printf("%s\n", info.name().c_str());
  printf("%s\n", info.bare_name().c_str());

并得到:

0
0
0
0
0
0
N10chaiscript8dispatch14Dynamic_ObjectE
N10chaiscript8dispatch14Dynamic_ObjectE

Boxed_Value::get_attr 供内部使用(我真的需要记录它。现在记下来。)它通常可以用于将属性应用于 any 类型的对象。这些是 not 属性,可以在 ChaiScript 中使用 .name 符号按名称查找。

您想要的功能是chaiscript::dispatch::Dynamic_Object::get_attr()Dynamic_Object 是实现 ChaiScript 定义对象的 C++ 类型。

要访问它,您需要:

int main()
{
  chaiscript::ChaiScript chai;
  const chaiscript::dispatch::Dynamic_Object &test_value = chai.eval_file<const chaiscript::dispatch::Dynamic_Object &>("script.chai");
  chaiscript::Boxed_Value number = test_value.get_attr("number");
  std::cout << chaiscript::boxed_cast<int>(number) << std::endl;
}

您也可以调用 test_value.get_attrs() 来获取对象的完整命名属性集。