Execute the script by calling the main() function
| 357 | |
| 358 | // Execute the script by calling the main() function |
| 359 | int ExecuteScript(asIScriptEngine *engine, const char *scriptFile) |
| 360 | { |
| 361 | asIScriptModule *mod = engine->GetModule("script", asGM_ONLY_IF_EXISTS); |
| 362 | if( !mod ) return -1; |
| 363 | |
| 364 | // Find the main function |
| 365 | asIScriptFunction *func = mod->GetFunctionByDecl("int main()"); |
| 366 | if( func == 0 ) |
| 367 | { |
| 368 | // Try again with "void main()" |
| 369 | func = mod->GetFunctionByDecl("void main()"); |
| 370 | } |
| 371 | |
| 372 | if( func == 0 ) |
| 373 | { |
| 374 | engine->WriteMessage(scriptFile, 0, 0, asMSGTYPE_ERROR, "Cannot find 'int main()' or 'void main()'"); |
| 375 | return -1; |
| 376 | } |
| 377 | |
| 378 | if(g_doDebug) |
| 379 | InitializeDebugger(engine); |
| 380 | |
| 381 | // Once we have the main function, we first need to initialize the global variables |
| 382 | // Since we've set up the request context callback we will be able to debug the |
| 383 | // initialization without passing in a pre-created context |
| 384 | int r = mod->ResetGlobalVars(0); |
| 385 | if( r < 0 ) |
| 386 | { |
| 387 | engine->WriteMessage(scriptFile, 0, 0, asMSGTYPE_ERROR, "Failed while initializing global variables"); |
| 388 | return -1; |
| 389 | } |
| 390 | |
| 391 | // Set up a context to execute the script |
| 392 | // The context manager will request the context from the |
| 393 | // pool, which will automatically attach the debugger |
| 394 | asIScriptContext *ctx = g_ctxMgr->AddContext(engine, func, true); |
| 395 | |
| 396 | // Execute the script until completion |
| 397 | // The script may create co-routines. These will automatically |
| 398 | // be managed by the context manager |
| 399 | while( g_ctxMgr->ExecuteScripts() ); |
| 400 | |
| 401 | // Check if the main script finished normally |
| 402 | r = ctx->GetState(); |
| 403 | if( r != asEXECUTION_FINISHED ) |
| 404 | { |
| 405 | if( r == asEXECUTION_EXCEPTION ) |
| 406 | { |
| 407 | cout << "The script failed with an exception" << endl; |
| 408 | cout << GetExceptionInfo(ctx, true).c_str(); |
| 409 | r = -1; |
| 410 | } |
| 411 | else if( r == asEXECUTION_ABORTED ) |
| 412 | { |
| 413 | cout << "The script was aborted" << endl; |
| 414 | r = -1; |
| 415 | } |
| 416 | else |
no test coverage detected