MCPcopy Create free account
hub / github.com/ChaiScript/ChaiScript / main

Function main

samples/inheritance.cpp:70–133  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

68};
69
70int main()
71{
72 chaiscript::ChaiScript chai;
73 chai.add(chaiscript::fun(&BaseClass::doSomething), "doSomething");
74 chai.add(chaiscript::fun(&BaseClass::setValue), "setValue");
75 chai.add(chaiscript::fun(&BaseClass::getValue), "getValue");
76 chai.add(chaiscript::constructor<ChaiScriptDerived (const std::vector<chaiscript::Boxed_Value> &)>(), "ChaiScriptDerived");
77 chai.add(chaiscript::base_class<BaseClass, ChaiScriptDerived>());
78 chai.add(chaiscript::user_type<BaseClass>(), "BaseClass");
79 chai.add(chaiscript::user_type<ChaiScriptDerived>(), "ChaiScriptDerived");
80
81 std::string script = R""(
82 def MakeDerived() {
83 return ChaiScriptDerived(
84 // create a dynamically created array and pass it in to the constructor
85 [
86 fun(this, f, d) {
87 // see here that we are calling back into the 'this' pointer
88 return "${this.getValue()}${f * d}";
89 },
90
91 fun(this, new_val) {
92 if (new_val.size() < 5) {
93 true;
94 } else {
95 print("String ${new_val} is too long");
96 false;
97 }
98 }
99 ]
100 );
101 }
102
103 var myderived := MakeDerived(); // avoid a copy by using reference assignment :=
104
105 )"";
106
107 chai.eval(script);
108
109 BaseClass &myderived = chai.eval<ChaiScriptDerived&>("myderived");
110
111 // at this point in the code myderived is both a ChaiScript variable and a C++ variable. In both cases
112 // it is a derivation of BaseClass, and the implementation is provided via ChaiScript functors
113 // assigned in the MakeDerived() factory function
114 //
115 // Notice that our validateValue() function has a requirement that the new string be < 5 characters long
116
117 myderived.setValue("1234");
118 assert(myderived.getValue() == "1234");
119
120 // chaiscript defined function will print out an error message and refuse to allow the setting
121 myderived.setValue("12345");
122 assert(myderived.getValue() == "1234");
123
124
125 chai.eval(R"(myderived.setValue("new"))"); // set the value via chaiscript
126 assert(myderived.getValue() == "new");
127

Callers

nothing calls this directly

Calls 5

funFunction · 0.85
getValueMethod · 0.80
addMethod · 0.45
evalMethod · 0.45
setValueMethod · 0.45

Tested by

no test coverage detected