lua_init.c 1.8 KB

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