/src/bindings/bind_main.cpp

https://bitbucket.org/vivkin/gam3b00bs/ · C++ · 67 lines · 46 code · 14 blank · 7 comment · 4 complexity · 36fb9c6c190acd9d81174aca7a9230d4 MD5 · raw file

  1. #include "common.h"
  2. #include "bind_all.h"
  3. #ifndef MAX_PATH
  4. #define MAX_PATH 260
  5. #endif
  6. namespace luab
  7. {
  8. static const char* g_script_dir = "../scripts";
  9. // loads and executes Lua script
  10. // NOTE: assumes the cwd is where the exe is.
  11. static int f_include( struct lua_State* L )
  12. {
  13. const char* filename;
  14. size_t sz;
  15. char path[ MAX_PATH ];
  16. filename = luaL_checklstring( L, 1, &sz );
  17. sprintf( path, "%s/%s", g_script_dir, filename );
  18. if( luaL_loadfile( L, path ) || (lua_call( L, 0, LUA_MULTRET ),0) )
  19. {
  20. lua_error( L );
  21. }
  22. return 0;
  23. }
  24. //////////////////////////////////////////////////////////////////////////
  25. static void bind_all( lua_State* L )
  26. {
  27. lua_register( L, "include", &f_include );
  28. // Call bindings here...
  29. bind_app( L );
  30. bind_renderer( L );
  31. bind_input( L );
  32. }
  33. //////////////////////////////////////////////////////////////////////////
  34. // works by simply calling the above f_include() for "main.lia" through lua state.
  35. // this way, an unhandled error prints the message and stack trace to stderr
  36. int start_scripts()
  37. {
  38. int ret = 1;
  39. lua_State* L = luaL_newstate();
  40. luaL_openlibs(L);
  41. bind_all(L);
  42. lua_getglobal( L, "debug" ); lua_getfield( L, -1, "traceback" ); // traceback function @ -3
  43. lua_pushcfunction( L, &f_include ); // loader function @ -2
  44. lua_pushstring( L, "main.lua" ); // module name @ -1
  45. if( 0 != lua_pcall( L, 1, LUA_MULTRET, -3 ) )
  46. {
  47. fprintf( stderr, "%s\n", lua_tostring( L, -1 ) ); // error message and stack trace
  48. ret = 0;
  49. }
  50. lua_close( L );
  51. return 0;
  52. }
  53. }