fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <stdexcept>
  5.  
  6. #include <lua.hpp>
  7.  
  8.  
  9. class Interpreter {
  10. public:
  11. // initialize lua and import libraries; handle error
  12. Interpreter() {
  13. luaState = luaL_newstate();
  14.  
  15. if(!luaState)
  16. throw std::runtime_error("initializing lua failed");
  17.  
  18. luaL_openlibs(luaState);
  19. }
  20.  
  21. ~Interpreter() {
  22. lua_close(luaState);
  23. }
  24.  
  25. // executes a string in the current lua state
  26. void executeCommand(std::string command) {
  27. bool err = luaL_dostring(luaState, command.c_str());
  28.  
  29. if(err)
  30. reportError();
  31. }
  32.  
  33. // executes a file in the current lua state
  34. void executeFile(std::string file) {
  35. bool err = luaL_loadfile(luaState, file.c_str());
  36.  
  37. // could not load file
  38. if(err)
  39. reportError();
  40.  
  41. else {
  42. bool err = lua_pcall(luaState, 0, 0, 0);
  43.  
  44. // could not execute file
  45. if(err)
  46. reportError();
  47. }
  48. }
  49.  
  50. private:
  51. lua_State* luaState;
  52.  
  53. // get error from top of stack, pop it from the stack and report it
  54. void reportError() {
  55. std::string err = lua_tostring(luaState, -1);
  56. lua_pop(luaState, 1);
  57.  
  58. std::cerr << err << std::endl;
  59. }
  60. };
  61.  
  62.  
  63. int main(int argc, char** argv) {
  64. std::vector<std::string> args(argv, argv + argc);
  65.  
  66. if(args.size() != 3) {
  67. std::cerr << "usage:\n ./a.out -cmd command\n ./a.out -file file" << std::endl;
  68. } else {
  69. // throws on failed initialization, see above
  70. Interpreter li;
  71.  
  72. if(args[1] == "-cmd")
  73. li.executeCommand(args[2]);
  74. else if(args[1] == "-file")
  75. li.executeFile(args[2]);
  76. }
  77. }
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty