lua.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. ** lua.c
  3. ** Linguagem para Usuarios de Aplicacao
  4. */
  5. char *rcs_lua="$Id: lua.c,v 1.9 1996/04/23 12:43:07 roberto Exp roberto $";
  6. #include <stdio.h>
  7. #include <string.h>
  8. #include "lua.h"
  9. #include "lualib.h"
  10. static int lua_argc;
  11. static char **lua_argv;
  12. #ifdef POSIX
  13. /*
  14. ** although this function is POSIX, there is no standard header file that
  15. ** defines it
  16. */
  17. int isatty (int fd);
  18. #else
  19. #define isatty(x) (x==0) /* assume stdin is a tty */
  20. #endif
  21. /*
  22. %F Allow Lua code to access argv strings.
  23. %i Receive from Lua the argument number (starting with 1).
  24. %o Return to Lua the argument, or nil if it does not exist.
  25. */
  26. static void lua_getargv (void)
  27. {
  28. lua_Object lo = lua_getparam(1);
  29. if (!lua_isnumber(lo))
  30. lua_pushnil();
  31. else
  32. {
  33. int n = (int)lua_getnumber(lo);
  34. if (n < 1 || n > lua_argc) lua_pushnil();
  35. else lua_pushstring(lua_argv[n]);
  36. }
  37. }
  38. static void manual_input (void)
  39. {
  40. if (isatty(0))
  41. {
  42. char buffer[250];
  43. while (fgets(buffer, sizeof(buffer), stdin) != 0)
  44. lua_dostring(buffer);
  45. }
  46. else
  47. lua_dofile(NULL); /* executes stdin as a file */
  48. }
  49. int main (int argc, char *argv[])
  50. {
  51. int i;
  52. int result = 0;
  53. iolib_open ();
  54. strlib_open ();
  55. mathlib_open ();
  56. lua_register("argv", lua_getargv);
  57. if (argc < 2)
  58. manual_input();
  59. else
  60. {
  61. for (i=1; i<argc; i++)
  62. if (strcmp(argv[i], "--") == 0)
  63. {
  64. lua_argc = argc-i-1;
  65. lua_argv = argv+i;
  66. break;
  67. }
  68. for (i=1; i<argc; i++)
  69. {
  70. if (strcmp(argv[i], "--") == 0)
  71. break;
  72. else if (strcmp(argv[i], "-") == 0)
  73. manual_input();
  74. else if (strcmp(argv[i], "-v") == 0)
  75. printf("%s %s\n(written by %s)\n\n",
  76. LUA_VERSION, LUA_COPYRIGHT, LUA_AUTHORS);
  77. else
  78. {
  79. result = lua_dofile (argv[i]);
  80. if (result)
  81. fprintf(stderr, "lua: error trying to run file %s\n", argv[i]);
  82. }
  83. }
  84. }
  85. return result;
  86. }