lua.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. /*
  2. ** $Id: lua.c,v 1.7 1997/12/03 19:57:54 roberto Exp roberto $
  3. ** Lua stand-alone interpreter
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <stdio.h>
  7. #include <string.h>
  8. #include "lua.h"
  9. #include "luadebug.h"
  10. #include "lualib.h"
  11. #ifndef OLD_ANSI
  12. #include <locale.h>
  13. #else
  14. #define setlocale(a,b) 0
  15. #endif
  16. #ifdef _POSIX_SOURCE
  17. #include <unistd.h>
  18. #else
  19. #define isatty(x) (x==0) /* assume stdin is a tty */
  20. #endif
  21. static void assign (char *arg)
  22. {
  23. if (strlen(arg) >= 500)
  24. fprintf(stderr, "lua: shell argument too long");
  25. else {
  26. char buffer[500];
  27. char *eq = strchr(arg, '=');
  28. lua_pushstring(eq+1);
  29. strncpy(buffer, arg, eq-arg);
  30. buffer[eq-arg] = 0;
  31. lua_setglobal(buffer);
  32. }
  33. }
  34. static void manual_input (void)
  35. {
  36. if (isatty(0)) {
  37. char buffer[250];
  38. while (1) {
  39. lua_beginblock();
  40. printf("%s", lua_getstring(lua_getglobal("_PROMPT")));
  41. if (fgets(buffer, sizeof(buffer), stdin) == 0)
  42. break;
  43. lua_dostring(buffer);
  44. lua_endblock();
  45. }
  46. printf("\n");
  47. }
  48. else
  49. lua_dofile(NULL); /* executes stdin as a file */
  50. }
  51. int main (int argc, char *argv[])
  52. {
  53. int i;
  54. setlocale(LC_ALL, "");
  55. lua_iolibopen();
  56. lua_strlibopen();
  57. lua_mathlibopen();
  58. lua_pushstring("> "); lua_setglobal("_PROMPT");
  59. if (argc < 2) {
  60. printf("%s %s\n", LUA_VERSION, LUA_COPYRIGHT);
  61. manual_input();
  62. }
  63. else for (i=1; i<argc; i++) {
  64. if (strcmp(argv[i], "-") == 0)
  65. manual_input();
  66. else if (strcmp(argv[i], "-d") == 0)
  67. lua_debug = 1;
  68. else if (strcmp(argv[i], "-v") == 0)
  69. printf("%s %s\n(written by %s)\n\n",
  70. LUA_VERSION, LUA_COPYRIGHT, LUA_AUTHORS);
  71. else if (strcmp(argv[i], "-e") == 0) {
  72. i++;
  73. if (lua_dostring(argv[i]) != 0) {
  74. fprintf(stderr, "lua: error running argument `%s'\n", argv[i]);
  75. return 1;
  76. }
  77. }
  78. else if (strchr(argv[i], '='))
  79. assign(argv[i]);
  80. else {
  81. int result = lua_dofile(argv[i]);
  82. if (result) {
  83. if (result == 2) {
  84. fprintf(stderr, "lua: cannot execute file ");
  85. perror(argv[i]);
  86. }
  87. return 1;
  88. }
  89. }
  90. }
  91. #ifdef DEBUG
  92. lua_close();
  93. #endif
  94. return 0;
  95. }