lua_init.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #include <dirent.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <lub/string.h>
  5. #include "private.h"
  6. <<<<<<< HEAD
  7. char *scripts_path = NULL;
  8. =======
  9. >>>>>>> b9e9072034ce6f652f230161cea580b52cf5a9b9
  10. static bool_t
  11. load_scripts(lua_State *L, char *path)
  12. {
  13. struct dirent *entry;
  14. DIR *dir = opendir(path);
  15. bool_t result = BOOL_FALSE;
  16. int res = 0;
  17. const char *ext_lua = ".lua";
  18. const char *ext_bin = ".bin";
  19. if (!dir) {
  20. printf("%s: Failed to open '%s' directory\n", __func__, path);
  21. return BOOL_FALSE;
  22. }
  23. for (entry = readdir(dir); entry; entry = readdir(dir)) {
  24. const char *extension = strrchr(entry->d_name, '.');
  25. /* check the filename */
  26. if ((extension) &&
  27. ((!strcmp(ext_lua, extension)) ||
  28. (!strcmp(ext_bin, extension)))) {
  29. char *filename = NULL;
  30. lub_string_cat(&filename, path);
  31. lub_string_cat(&filename, "/");
  32. lub_string_cat(&filename, entry->d_name);
  33. result = BOOL_FALSE;
  34. if ((res = luaL_loadfile(L, filename))) {
  35. l_print_error(L, __func__, "load", res);
  36. } else if ((res = lua_pcall(L, 0, 0, 0))) {
  37. l_print_error(L, __func__, "exec", res);
  38. } else
  39. result = BOOL_TRUE;
  40. lub_string_free(filename);
  41. /* Shouldn't happen, but we can't be too sure ;-) */
  42. while(lua_gettop(L))
  43. lua_pop(L, 1);
  44. if (!result)
  45. break;
  46. }
  47. }
  48. closedir(dir);
  49. return result;
  50. }
  51. int clish_plugin_init_lua(clish_shell_t *shell)
  52. {
  53. lua_State *L = NULL;
  54. <<<<<<< HEAD
  55. =======
  56. char *scripts_path = getenv("CLISH_SCRIPTS_PATH");
  57. if (!scripts_path)
  58. if(!(scripts_path = getenv("CLISH_PATH"))) {
  59. printf("%s: Lua scripts dir not specified\n", __func__);
  60. return (-1);
  61. }
  62. >>>>>>> b9e9072034ce6f652f230161cea580b52cf5a9b9
  63. if (!(L = luaL_newstate())) {
  64. printf("%s: Failed to instantiate Lua interpreter\n", __func__);
  65. return (-1);
  66. }
  67. luaL_openlibs(L);
  68. <<<<<<< HEAD
  69. if (scripts_path && !load_scripts(L, scripts_path)) {
  70. =======
  71. if (!load_scripts(L, scripts_path)) {
  72. >>>>>>> b9e9072034ce6f652f230161cea580b52cf5a9b9
  73. return (-1);
  74. }
  75. clish_shell__set_udata(shell, LUA_UDATA, L);
  76. lua_pushlightuserdata(L, shell);
  77. lua_setglobal(L, "clish_shell");
  78. return (0);
  79. }