lua_init.c 1.7 KB

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