3

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

这是我的 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()是真的。我显然做错了什么,但我找不到我的错误。
或者也许它不打算以这种方式使用?

4

2 回答 2

3

Boxed_Value::get_attr用于内部使用(我真的需要记录它。现在记下它。)它通常可以用于将属性应用于任何类型的对象。这些不是可以在 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()以获取对象的完整命名属性集。

于 2015-12-21T05:21:38.423 回答
1

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

  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
于 2015-12-20T09:28:16.927 回答