bool TestExecuteScript() { bool fail = false; COutStream out; engine = asCreateScriptEngine(ANGELSCRIPT_VERSION); engine->SetMessageCallback(asMETHOD(COutStream,Callback), &out, asCALL_THISCALL); RegisterStdString(engine); engine->RegisterGlobalFunction("void assert(bool)", asFUNCTION(Assert), asCALL_GENERIC); CScriptBuilder builder; int r = builder.StartNewModule(engine, 0); if( r >= 0 ) r = builder.AddSectionFromFile("scripts/TestExecuteScript.as"); if( r >= 0 ) r = builder.BuildModule(); if( r >= 0 ) { fail = ExecuteScript(); } engine->Release(); engine = NULL; return fail; }
bool CommonAPI::InitAS() { engine = asCreateScriptEngine(ANGELSCRIPT_VERSION); engine->SetMessageCallback(asFUNCTION(MessageCallback), 0, asCALL_CDECL); RegisterStdString(engine); RegisterAPI(); CScriptBuilder builder; if(builder.StartNewModule(engine, "MyModule") < 0) FILE_LOG(logERROR) << "Unrecoverable error while starting a new module."; string scriptPath = exePath.substr(0, exePath.find_last_of(".")).append(".tes"); if(builder.AddSectionFromFile(scriptPath.c_str()) < 0) FILE_LOG(logERROR) << "Unable to load script." << scriptPath; else FILE_LOG(logINFO) << "Script " << scriptPath << " loaded successfully."; if(builder.BuildModule() < 0) FILE_LOG(logERROR) << "Please correct the errors in the script and try again."; module = engine->GetModule("MyModule"); return true; }
//====================================================================== HSISCRIPT CScriptInt::LoadScript(const std::string& szScriptName) { //Load script if ((!this->m_bInitialized) || (!szScriptName.length())) return SI_INVALID_ID; CScriptBuilder oScriptBuilder; //Start new module if (AS_FAILED(oScriptBuilder.StartNewModule(this->m_pScriptEngine, szScriptName.c_str()))) return SI_INVALID_ID; //Add script file to module if (AS_FAILED(oScriptBuilder.AddSectionFromFile((/*this->m_szScriptPath +*/ szScriptName/* + ".as"*/).c_str()))) return SI_INVALID_ID; //Build script module if (AS_FAILED(oScriptBuilder.BuildModule())) return SI_INVALID_ID; //Setup struct si_script_s sScriptData; sScriptData.szName = szScriptName; sScriptData.pModule = this->m_pScriptEngine->GetModule(szScriptName.c_str()); //Get pointer to script module if (!sScriptData.pModule) return SI_INVALID_ID; //Add to list this->m_vScripts.push_back(sScriptData); return this->m_vScripts.size() - 1; //Return entry ID }
bool ASXEngine::load_and_build_script(const std::string& filename, const std::string& moduleName) { CScriptBuilder builder; if(builder.StartNewModule(m_engine, moduleName.c_str()) < 0) return false; if(builder.AddSectionFromFile(filename.c_str()) < 0) return false; return builder.BuildModule() == 0; }
bool cSqScript::CreateFromFile(const tString& asFileName) { CScriptBuilder builder; builder.StartNewModule(mpScriptEngine,msModuleName.c_str()); if(builder.AddSectionFromFile(asFileName.c_str())<0) { Error("Couldn't add script '%s'!\n",asFileName.c_str()); return false; } if(builder.BuildModule()<0) { Error("Couldn't build script '%s'!\n",asFileName.c_str()); Log("------- SCRIPT OUTPUT BEGIN --------------------------\n"); mpScriptOutput->Display(); mpScriptOutput->Clear(); Log("------- SCRIPT OUTPUT END ----------------------------\n"); return false; } mpScriptOutput->Clear(); return true; }
//************************************ // Method: LoadScript // FullName: ScriptEngine::LoadScript // Access: public // Returns: bool // Qualifier: // Parameter: const char * filename Name of the scripted file to load //************************************ bool ScriptEngine::LoadScript(const char* filename, const char* module) { CScriptBuilder builder; bool OK = builder.StartNewModule(m_engine, module) > 0; OK = OK && (builder.AddSectionFromFile(filename) > 0); OK = OK && (builder.BuildModule() > 0); return OK; }
NEPHILIM_NS_BEGIN bool ASXModuleBuilder::load(ASXEngine& engine, const String& filename, const String& module) { CScriptBuilder builder; builder.StartNewModule(engine.get(), module.c_str()); builder.AddSectionFromFile(filename.c_str()); if(builder.BuildModule() > 0) { return true; } else { return false; } }
int CompileScript(asIScriptEngine *engine) { int r; // The builder is a helper class that will load the script file, // search for #include directives, and load any included files as // well. CScriptBuilder builder; // Build the script. If there are any compiler messages they will // be written to the message stream that we set right after creating the // script engine. If there are no errors, and no warnings, nothing will // be written to the stream. r = builder.StartNewModule(engine, 0); if( r < 0 ) { cout << "Failed to start new module" << endl; return r; } r = builder.AddSectionFromFile("script.as"); if( r < 0 ) { cout << "Failed to add script file" << endl; return r; } r = builder.BuildModule(); if( r < 0 ) { cout << "Failed to build the module" << endl; return r; } // The engine doesn't keep a copy of the script sections after Build() has // returned. So if the script needs to be recompiled, then all the script // sections must be added again. // If we want to have several scripts executing at different times but // that have no direct relation with each other, then we can compile them // into separate script modules. Each module use their own namespace and // scope, so function names, and global variables will not conflict with // each other. return 0; }
int CompileScript(asIScriptEngine *engine, const char *scriptFile) { int r; CScriptBuilder builder; r = builder.StartNewModule(engine, "build"); if( r < 0 ) return -1; r = builder.AddSectionFromFile(scriptFile); if( r < 0 ) return -1; r = builder.BuildModule(); if( r < 0 ) { engine->WriteMessage(scriptFile, 0, 0, asMSGTYPE_ERROR, "Script failed to build"); return -1; } engine->WriteMessage(scriptFile, 0, 0, asMSGTYPE_INFORMATION, "Script successfully built"); return 0; }
void run(GLFWwindow* window, std::string const& scriptFile) { asIScriptEngine* engine = asCreateScriptEngine(ANGELSCRIPT_VERSION); anglhck::registerToEngine(engine); RegisterStdString(engine); engine->RegisterGlobalFunction("void print(const string &in)", asFUNCTION(print), asCALL_CDECL); CScriptBuilder builder; builder.StartNewModule(engine, "MyModule"); builder.AddSectionFromFile(scriptFile); builder.BuildModule(); asIScriptModule *mod = engine->GetModule("MyModule"); asIScriptFunction *func = mod->GetFunctionByDecl("void main()"); asIScriptContext *ctx = engine->CreateContext(); ctx->Prepare(func); int ret = ctx->Execute(); if( ret == asEXECUTION_EXCEPTION ) { std::cout << ctx->GetExceptionString() << std::endl; } }
int CompileScript(asIScriptEngine *engine, const char *scriptFile) { int r; // We will only initialize the global variables once we're // ready to execute, so disable the automatic initialization engine->SetEngineProperty(asEP_INIT_GLOBAL_VARS_AFTER_BUILD, false); CScriptBuilder builder; r = builder.StartNewModule(engine, "script"); if( r < 0 ) return -1; r = builder.AddSectionFromFile(scriptFile); if( r < 0 ) return -1; r = builder.BuildModule(); if( r < 0 ) { engine->WriteMessage(scriptFile, 0, 0, asMSGTYPE_ERROR, "Script failed to build"); return -1; } return 0; }
bool Test() { bool fail = false; int r = 0; COutStream out; // TODO: Preprocessor directives should be alone on the line asIScriptEngine *engine = asCreateScriptEngine(ANGELSCRIPT_VERSION); RegisterScriptArray(engine, true); engine->SetMessageCallback(asMETHOD(COutStream,Callback), &out, asCALL_THISCALL); RegisterScriptMathComplex(engine); // Test the parse token method asETokenClass t = engine->ParseToken("!is"); if( t != asTC_KEYWORD ) TEST_FAILED; // Compile a script with meta data strings CScriptBuilder builder; builder.DefineWord("COMPILE"); r = builder.StartNewModule(engine, 0); r = builder.AddSectionFromMemory(script); r = builder.BuildModule(); #if AS_PROCESS_METADATA == 1 if( r < 0 ) TEST_FAILED; int funcId = engine->GetModule(0)->GetFunctionIdByName("func1"); string metadata = builder.GetMetadataStringForFunc(funcId); if( metadata != " my meta data test " ) TEST_FAILED; funcId = engine->GetModule(0)->GetFunctionIdByName("func2"); metadata = builder.GetMetadataStringForFunc(funcId); if( metadata != " test['hello'] " ) TEST_FAILED; int typeId = engine->GetModule(0)->GetTypeIdByDecl("MyClass"); metadata = builder.GetMetadataStringForType(typeId); if( metadata != " myclass " ) TEST_FAILED; typeId = engine->GetModule(0)->GetTypeIdByDecl("MyClass2"); metadata = builder.GetMetadataStringForTypeProperty(typeId, 0); if( metadata != " edit " ) TEST_FAILED; metadata = builder.GetMetadataStringForTypeProperty(typeId, 1); if( metadata != " noedit " ) TEST_FAILED; metadata = builder.GetMetadataStringForTypeProperty(typeId, 2); if( metadata != " edit,c " ) TEST_FAILED; typeId = engine->GetModule(0)->GetTypeIdByDecl("MyIntf"); metadata = builder.GetMetadataStringForType(typeId); if( metadata != " myintf " ) TEST_FAILED; int varIdx = engine->GetModule(0)->GetGlobalVarIndexByName("g_var"); metadata = builder.GetMetadataStringForVar(varIdx); if( metadata != " init " ) TEST_FAILED; varIdx = engine->GetModule(0)->GetGlobalVarIndexByName("g_obj"); metadata = builder.GetMetadataStringForVar(varIdx); if( metadata != " var of type myclass " ) TEST_FAILED; #endif engine->Release(); return fail; }
bool ScriptManager::loadFromMemory(const std::string& name, const void* data, size_t len, ScriptType type) { std::string lower; std::transform(name.begin(), name.end(), std::back_inserter(lower), ::tolower); if (type == Type_Autodetect) { if (lower.substr(lower.size() - 4) == ".asb") type = Type_Bytecode; else if (lower.substr(lower.size() - 3) == ".as") type = Type_Text; else return false; } bool reload = mScripts.count(lower) > 0; std::list<asIScriptObject*> changes; asIScriptModule* module = mEngine->GetModule(lower.c_str(), asGM_ONLY_IF_EXISTS); CSerializer serial; if (reload && module) { for (auto& reg : mSerializers) serial.AddUserType(reg.second(), reg.first); for (auto it = mChangeNotice.begin(); it != mChangeNotice.end();) { if (it->second.WeakRef->Get()) { it->second.WeakRef->Release(); it = mChangeNotice.erase(it); continue; } auto* obj = it->first; if (obj->GetObjectType()->GetModule() == module) { serial.AddExtraObjectToStore(obj); changes.push_back(it->first); } ++it; } serial.Store(module); } BytecodeStore bcode; if (type == Type_Text) { static const char* scratchName = "!!ScratchSpace!!"; CScriptBuilder builder; for (auto& def : mDefines) builder.DefineWord(def.c_str()); builder.StartNewModule(mEngine, scratchName); for (auto& callback : mPreLoadCallbacks) if (!callback.second(builder.GetModule())) { mEngine->DiscardModule(scratchName); return false; } builder.AddSectionFromMemory(lower.c_str(), (const char*)data, len); int r = builder.BuildModule(); if (r < 0) { #ifndef NDEBUG puts(ASException::GetMessage(r)); #endif return false; } #ifdef NDEBUG builder.GetModule()->SaveByteCode(&bcode, true); #else builder.GetModule()->SaveByteCode(&bcode, false); #endif mEngine->DiscardModule(scratchName); } else { bcode = BytecodeStore((const char*)data, len); } if (module) module->Discard(); module = mEngine->GetModule(lower.c_str(), asGM_ALWAYS_CREATE); // FIXME? Preload callbacks can not act on bytecode anyway /* if (type == Type_Bytecode) for (auto& callback : mPreLoadCallbacks) if (!callback.second(module)) { module->Discard(); return false; } */ int r = module->LoadByteCode(&bcode); if (r < 0) { module->Discard(); return false; } module->BindAllImportedFunctions(); if (mScripts.count(lower) == 0) { mScripts[lower].Name = name; mScripts[lower].DirectLoad = true; } if (reload) { serial.Restore(module); for (auto& it : changes) { auto* newObj = (asIScriptObject*)serial.GetPointerToRestoredObject(it); auto notice = mChangeNotice[it]; mChangeNotice.erase(it); notice.WeakRef->Release(); notice.Callback(newObj); } mEngine->GarbageCollect(asGC_FULL_CYCLE); } return true; }
CScriptMgr::SController *CScriptMgr::GetControllerScript(const string &script) { int r; // Find the cached controller for( unsigned int n = 0; n < controllers.size(); n++ ) { if( controllers[n]->module == script ) return controllers[n]; } // No controller, check if the script has already been loaded asIScriptModule *mod = engine->GetModule(script.c_str(), asGM_ONLY_IF_EXISTS); if( mod ) { // We've already attempted loading the script before, but there is no controller return 0; } // Compile the script into the module CScriptBuilder builder; r = builder.StartNewModule(engine, script.c_str()); if( r < 0 ) return 0; // If the script file doesn't exist, then there is no script controller for this type FILE *f; if( (f = fopen((script + ".as").c_str(), "r")) == 0 ) return 0; fclose(f); // Let the builder load the script, and do the necessary pre-processing (include files, etc) r = builder.AddSectionFromFile((script + ".as").c_str()); if( r < 0 ) return 0; r = builder.BuildModule(); if( r < 0 ) return 0; // Cache the functions and methods that will be used SController *ctrl = new SController; controllers.push_back(ctrl); ctrl->module = script; // Find the class that implements the IController interface mod = engine->GetModule(script.c_str(), asGM_ONLY_IF_EXISTS); asIObjectType *type = 0; int tc = mod->GetObjectTypeCount(); for( int n = 0; n < tc; n++ ) { bool found = false; type = mod->GetObjectTypeByIndex(n); int ic = type->GetInterfaceCount(); for( int i = 0; i < ic; i++ ) { if( strcmp(type->GetInterface(i)->GetName(), "IController") == 0 ) { found = true; break; } } if( found == true ) { ctrl->type = type; break; } } if( ctrl->type == 0 ) { cout << "Couldn't find the controller class for the type '" << script << "'" << endl; controllers.pop_back(); delete ctrl; return 0; } // Find the factory function // The game engine will pass in the owning CGameObj to the controller for storage string s = string(type->GetName()) + "@ " + string(type->GetName()) + "(CGameObj @)"; ctrl->factoryFunc = type->GetFactoryByDecl(s.c_str()); if( ctrl->factoryFunc == 0 ) { cout << "Couldn't find the appropriate factory for the type '" << script << "'" << endl; controllers.pop_back(); delete ctrl; return 0; } // Find the optional event handlers ctrl->onThinkMethod = type->GetMethodByDecl("void OnThink()"); ctrl->onMessageMethod = type->GetMethodByDecl("void OnMessage(ref @msg, const CGameObj @sender)"); // Add the cache as user data to the type for quick access type->SetUserData(ctrl); return ctrl; }
int main() { // the return value int r; // Create the script engine asIScriptEngine *engine = asCreateScriptEngine(ANGELSCRIPT_VERSION); // Set the message callback to receive information on errors in human readable form. r = engine->SetMessageCallback(asFUNCTION(MessageCallback), 0, asCALL_CDECL); if( r < 0 ) { printf("Something went wrong\n"); engine->Release(); return 1; } // register std::strings RegisterStdString(engine); // Register the function that we want the scripts to call r = engine->RegisterGlobalFunction("void print(const string &in)", asFUNCTION(print), asCALL_CDECL); if( r < 0 ) { printf("Something went wrong with the print function asignment\n"); return 1; } r = engine->RegisterObjectType("Person", 0, asOBJ_REF | asOBJ_NOCOUNT); if( r < 0 ) { printf("Unable to register Person\n"); return 1; } r = engine->RegisterObjectProperty("Person", "float m_Happiness", asOFFSET(Person, m_Happiness)); if( r < 0 ) { printf("Registering the object failed\n"); return 1; } r = engine->RegisterObjectMethod("Person", "void AddStuff()", asMETHOD(Person, AddStuff), asCALL_THISCALL); if( r < 0 ) { printf("Registering function failed\n"); return 1; } r = engine->RegisterObjectMethod("Person", "void AddMoreStuff(int num)", asMETHOD(Person, AddMoreStuff), asCALL_THISCALL); if( r < 0 ) { printf("Registering function failed\n"); return 1; } // --------------- build a script ------------------------------------ CScriptBuilder builder; r = builder.StartNewModule(engine, "MyModule"); if( r < 0 ) { // If the code fails here it is usually because there // is no more memory to allocate the module printf("Unrecoverable error while starting a new module.\n"); return 1; } r = builder.AddSectionFromFile("Test1.as"); if( r < 0 ) { // The builder wasn't able to load the file. Maybe the file // has been removed, or the wrong name was given, or some // preprocessing commands are incorrectly written. printf("Please correct the errors in the script and try again.\n"); return 1; } r = builder.BuildModule(); if( r < 0 ) { // An error occurred. Instruct the script writer to fix the // compilation errors that were listed in the output stream. printf("Please correct the errors in the script and try again.\n"); return 1; } #if 0 r = engine->RegisterObjectProperty("Person", "float m_Happiness", asOFFSET(Person, m_Happiness)); if( r < 0 ) { printf("Registering the object failed\n"); return 1; } #endif // declare the person Person p; p.m_Age = 1; p.m_Happiness = 0.5; // -------------------- run the script ----------------------- // Find the function that is to be called. asIScriptModule *mod = engine->GetModule("MyModule"); #if 0 asIScriptFunction *func = mod->GetFunctionByDecl("void main()"); if( func == 0 ) { // The function couldn't be found. Instruct the script writer // to include the expected function in the script. printf("The script must have the function 'void main()'. Please add it and try again.\n"); return 1; } #endif asIScriptFunction *func = mod->GetFunctionByDecl("void Update(Person@ p)"); if( func == 0 ) { printf("Unable to find function 'Update'\n"); return 1; } // Create our context, prepare it, and then execute asIScriptContext *ctx = engine->CreateContext(); ctx->Prepare(func); printf("preparing function\n"); r = ctx->SetArgObject(0, &p); if( r < 0 ) { printf("Error in setting the object\n"); } else { printf("Argument set as object\n"); } r = ctx->Execute(); if( r != asEXECUTION_FINISHED ) { // The execution didn't complete as expected. Determine what happened. if( r == asEXECUTION_EXCEPTION ) { // An exception occurred, let the script writer know what happened so it can be corrected. printf("An exception '%s' occurred. Please correct the code and try again.\n", ctx->GetExceptionString()); } } ctx->Release(); printf("Person's happiness is now %f\n", p.m_Happiness); // clean up engine->Release(); return 0; }
bool Test() { bool fail = false; int r = 0; COutStream out; CBufferedOutStream bout; // TODO: Preprocessor directives should be alone on the line asIScriptEngine *engine = asCreateScriptEngine(ANGELSCRIPT_VERSION); RegisterScriptArray(engine, true); engine->SetMessageCallback(asMETHOD(COutStream,Callback), &out, asCALL_THISCALL); if( !strstr(asGetLibraryOptions(), "AS_MAX_PORTABILITY") ) RegisterScriptMathComplex(engine); else engine->RegisterObjectType("complex", 4, asOBJ_VALUE | asOBJ_POD); // Test the parse token method asETokenClass t = engine->ParseToken("!is"); if( t != asTC_KEYWORD ) TEST_FAILED; // Compile a script with meta data strings CScriptBuilder builder; builder.DefineWord("COMPILE"); r = builder.StartNewModule(engine, 0); r = builder.AddSectionFromMemory("", script); r = builder.BuildModule(); #if AS_PROCESS_METADATA == 1 if( r < 0 ) TEST_FAILED; asIScriptFunction *func = engine->GetModule(0)->GetFunctionByName("func1"); string metadata = builder.GetMetadataStringForFunc(func); if( metadata != " my meta data test " ) TEST_FAILED; func = engine->GetModule(0)->GetFunctionByName("func2"); metadata = builder.GetMetadataStringForFunc(func); if( metadata != " test['hello'] " ) TEST_FAILED; engine->GetModule(0)->SetDefaultNamespace("NS"); func = engine->GetModule(0)->GetFunctionByName("func"); metadata = builder.GetMetadataStringForFunc(func); if( metadata != "func" ) TEST_FAILED; engine->GetModule(0)->SetDefaultNamespace(""); int typeId = engine->GetModule(0)->GetTypeIdByDecl("MyClass"); metadata = builder.GetMetadataStringForType(typeId); if( metadata != " myclass " ) TEST_FAILED; typeId = engine->GetModule(0)->GetTypeIdByDecl("NS::Class"); metadata = builder.GetMetadataStringForType(typeId); if( metadata != "class" ) TEST_FAILED; typeId = engine->GetModule(0)->GetTypeIdByDecl("MyClass2"); metadata = builder.GetMetadataStringForTypeProperty(typeId, 0); if( metadata != " edit " ) TEST_FAILED; metadata = builder.GetMetadataStringForTypeProperty(typeId, 1); if( metadata != " noedit " ) TEST_FAILED; metadata = builder.GetMetadataStringForTypeProperty(typeId, 2); if( metadata != " edit,c " ) TEST_FAILED; asIObjectType *type = engine->GetObjectTypeById(typeId); if( type == 0 ) TEST_FAILED; else { metadata = builder.GetMetadataStringForTypeMethod(typeId, type->GetMethodByName("get_prop")); if( metadata != " prop " ) TEST_FAILED; metadata = builder.GetMetadataStringForTypeMethod(typeId, type->GetMethodByName("set_prop")); if( metadata != " prop " ) TEST_FAILED; } typeId = engine->GetModule(0)->GetTypeIdByDecl("MyIntf"); metadata = builder.GetMetadataStringForType(typeId); if( metadata != " myintf " ) TEST_FAILED; int varIdx = engine->GetModule(0)->GetGlobalVarIndexByName("g_var"); metadata = builder.GetMetadataStringForVar(varIdx); if( metadata != " init " ) TEST_FAILED; varIdx = engine->GetModule(0)->GetGlobalVarIndexByName("g_obj"); metadata = builder.GetMetadataStringForVar(varIdx); if( metadata != " var of type myclass " ) TEST_FAILED; #endif // http://www.gamedev.net/topic/624445-cscriptbuilder-asset-string-subscript-out-of-range/ { bout.buffer = ""; CScriptBuilder builder; builder.StartNewModule(engine, "mod"); builder.AddSectionFromMemory("", "#"); engine->SetMessageCallback(asMETHOD(CBufferedOutStream, Callback), &bout, asCALL_THISCALL); r = builder.BuildModule(); if( r >= 0 ) TEST_FAILED; if( bout.buffer != " (1, 1) : Error : Unexpected token '<unrecognized token>'\n" ) { printf("%s", bout.buffer.c_str()); TEST_FAILED; } } // Add a script section from memory with length { engine->SetMessageCallback(asMETHOD(COutStream, Callback), &bout, asCALL_THISCALL); CScriptBuilder builder; builder.StartNewModule(engine, "mod"); builder.AddSectionFromMemory("", "void func() {} $#", 14); r = builder.BuildModule(); if( r < 0 ) TEST_FAILED; } // http://www.gamedev.net/topic/631848-cscriptbuilder-bug/ { bout.buffer = ""; CScriptBuilder builder; builder.StartNewModule(engine, "mod"); builder.AddSectionFromMemory("", "class "); engine->SetMessageCallback(asMETHOD(CBufferedOutStream, Callback), &bout, asCALL_THISCALL); r = builder.BuildModule(); if( r >= 0 ) TEST_FAILED; if( bout.buffer != " (1, 7) : Error : Expected identifier\n" " (1, 7) : Error : Instead found '<end of file>'\n" " (1, 7) : Error : Expected '{'\n" " (1, 7) : Error : Instead found '<end of file>'\n" ) { printf("%s", bout.buffer.c_str()); TEST_FAILED; } } engine->Release(); return fail; }
bool PxfMain(String _CmdLine) { int r; // Create the script engine asIScriptEngine *engine = asCreateScriptEngine(ANGELSCRIPT_VERSION); engine->SetEngineProperty(asEP_SCRIPT_SCANNER, 0); // Set the message callback to receive information on errors in human readable form. // It's recommended to do this right after the creation of the engine, because if // some registration fails the engine may send valuable information to the message // stream. r = engine->SetMessageCallback(asFUNCTION(MessageCallback), 0, asCALL_CDECL); assert( r >= 0 ); // Register the function that we want the scripts to call r = engine->RegisterGlobalFunction("void print()", asFUNCTION(print), asCALL_CDECL); assert( r >= 0 ); // The CScriptBuilder helper is an add-on that loads the file, // performs a pre-processing pass if necessary, and then tells // the engine to build a script module. CScriptBuilder builder; r = builder.StartNewModule(engine, "MyModule"); r = builder.AddSectionFromFile("test.as"); r = builder.BuildModule(); if( r < 0 ) { // An error occurred. Instruct the script writer to fix the // compilation errors that were listed in the output stream. printf("Please correct the errors in the script and try again.\n"); return false; } // Find the function that is to be called. asIScriptModule *mod = engine->GetModule("MyModule"); int funcId = mod->GetFunctionIdByDecl("void main()"); if( funcId < 0 ) { // The function couldn't be found. Instruct the script writer // to include the expected function in the script. printf("The script must have the function 'void main()'. Please add it and try again.\n"); return false; } // Create our context, prepare it, and then execute asIScriptContext *ctx = engine->CreateContext(); ctx->Prepare(funcId); r = ctx->Execute(); if( r != asEXECUTION_FINISHED ) { // The execution didn't complete as expected. Determine what happened. if( r == asEXECUTION_EXCEPTION ) { // An exception occurred, let the script writer know what happened so it can be corrected. printf("An exception '%s' occurred. Please correct the code and try again.\n", ctx->GetExceptionString()); } } // Clean up ctx->Release(); engine->Release(); return true; }