MCPcopy Create free account
hub / github.com/OpenTTD/OpenTTD / Import

Method Import

src/script/api/script_controller.cpp:97–166  ·  view source on GitHub ↗

static */

Source from the content-addressed store, hash-verified

95}
96
97/* static */ HSQOBJECT ScriptController::Import(const std::string &library, const std::string &class_name, int version)
98{
99 ScriptController &controller = ScriptObject::GetActiveInstance().GetController();
100 Squirrel &engine = *ScriptObject::GetActiveInstance().engine;
101 HSQUIRRELVM vm = engine.GetVM();
102
103 ScriptInfo *lib = ScriptObject::GetActiveInstance().FindLibrary(library, version);
104 if (lib == nullptr) {
105 throw sq_throwerror(vm, fmt::format("couldn't find library '{}' with version {}", library, version));
106 }
107
108 /* Internally we store libraries as 'library.version' */
109 std::string library_name = fmt::format("{}.{}", library, version);
110
111 /* Get the current table/class we belong to */
112 HSQOBJECT parent;
113 sq_getstackobj(vm, 1, &parent);
114
115 std::string fake_class;
116
117 LoadedLibraryList::iterator it = controller.loaded_library.find(library_name);
118 if (it != controller.loaded_library.end()) {
119 fake_class = it->second;
120 } else {
121 int next_number = ++controller.loaded_library_count;
122
123 /* Create a new fake internal name */
124 fake_class = fmt::format("_internalNA{}", next_number);
125
126 /* Load the library in a 'fake' namespace, so we can link it to the name the user requested */
127 sq_pushroottable(vm);
128 sq_pushstring(vm, fake_class);
129 sq_newclass(vm, SQFalse);
130 /* Load the library */
131 if (!engine.LoadScript(vm, lib->GetMainScript(), false)) {
132 throw sq_throwerror(vm, fmt::format("there was a compile error when importing '{}' version {}", library, version));
133 }
134 /* Create the fake class */
135 sq_newslot(vm, -3, SQFalse);
136 sq_pop(vm, 1);
137
138 controller.loaded_library[library_name] = fake_class;
139 }
140
141 /* Find the real class inside the fake class (like 'sets.Vector') */
142 sq_pushroottable(vm);
143 sq_pushstring(vm, fake_class);
144 if (SQ_FAILED(sq_get(vm, -2))) {
145 throw sq_throwerror(vm, "internal error assigning library class");
146 }
147 sq_pushstring(vm, lib->GetInstanceName());
148 if (SQ_FAILED(sq_get(vm, -2))) {
149 throw sq_throwerror(vm, fmt::format("unable to find class '{}' in the library '{}' version {}", lib->GetInstanceName(), library, version));
150 }
151 HSQOBJECT obj;
152 sq_getstackobj(vm, -1, &obj);
153 sq_pop(vm, 3);
154

Callers

nothing calls this directly

Calls 15

sq_throwerrorFunction · 0.85
sq_getstackobjFunction · 0.85
sq_pushroottableFunction · 0.85
sq_pushstringFunction · 0.85
sq_newclassFunction · 0.85
sq_newslotFunction · 0.85
sq_popFunction · 0.85
sq_getFunction · 0.85
sq_pushobjectFunction · 0.85
GetVMMethod · 0.80
LoadScriptMethod · 0.80
GetMainScriptMethod · 0.80

Tested by

no test coverage detected