execute_function_1.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. #include <iterator>
  5. #include "gmThread.h"
  6. #include "gmCall.h"
  7. int gmLoadAndExecuteScript( gmMachine &a_machine, const char *a_filename )
  8. {
  9. std::ifstream file(a_filename);
  10. if (!file)
  11. return GM_EXCEPTION;
  12. std::string fileString = std::string(std::istreambuf_iterator<char>(file),
  13. std::istreambuf_iterator<char>());
  14. file.close();
  15. return a_machine.ExecuteString(fileString.c_str());
  16. }
  17. int main()
  18. {
  19. gmMachine gm;
  20. // Execute a simple script file
  21. gmLoadAndExecuteScript ( &gm, "scripts/function_test.gm" );
  22. gmVariable funcName, funcFound;
  23. funcName.SetString( gm.AllocStringObject("sayHello") );
  24. // find in global table
  25. funcFound = gm.GetGlobals()->Get(funcName);
  26. if ( funcFound.m_type != GM_FUNCTION )
  27. {
  28. std::cout << "Failed to find 'sayHello'";
  29. return 0;
  30. }
  31. // Get function object from variable
  32. gmFunctionObject *func = (gmFunctionObject *)funcFound.m_value.m_ref;
  33. gmThread *thread = gm.CreateThread();
  34. // Push empty 'this' value
  35. thread->Push( gmVariable::s_null );
  36. thread->PushFunction( func );
  37. // No params needed
  38. // Get a blank variable to grab the return
  39. gmVariable returnVar;
  40. // execute the thread
  41. int state = thread->PushStackFrame( 0 );
  42. if (state != gmThread::KILLED )
  43. {
  44. state = thread->Sys_Execute( &returnVar );
  45. }
  46. return 0;
  47. }