ReplInterpreterScriptLoader.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #if !(PCL || ENABLE_DOTNET)
  2. using System;
  3. using MoonSharp.Interpreter.Loaders;
  4. namespace MoonSharp.Interpreter.REPL
  5. {
  6. /// <summary>
  7. /// A script loader loading scripts directly from the file system (does not go through platform object)
  8. /// AND starts with module paths taken from environment variables (again, not going through the platform object).
  9. ///
  10. /// The paths are preconstructed using :
  11. /// * The MOONSHARP_PATH environment variable if it exists
  12. /// * The LUA_PATH_5_2 environment variable if MOONSHARP_PATH does not exists
  13. /// * The LUA_PATH environment variable if LUA_PATH_5_2 and MOONSHARP_PATH do not exists
  14. /// * The "?;?.lua" path if all the above fail
  15. ///
  16. /// Also, everytime a module is require(d), the "LUA_PATH" global variable is checked. If it exists, those paths
  17. /// will be used to load the module instead of the global ones.
  18. /// </summary>
  19. public class ReplInterpreterScriptLoader : FileSystemScriptLoader
  20. {
  21. /// <summary>
  22. /// Initializes a new instance of the <see cref="ReplInterpreterScriptLoader"/> class.
  23. /// </summary>
  24. public ReplInterpreterScriptLoader()
  25. {
  26. string env = Environment.GetEnvironmentVariable("MOONSHARP_PATH");
  27. if (!string.IsNullOrEmpty(env)) ModulePaths = UnpackStringPaths(env);
  28. if (ModulePaths == null)
  29. {
  30. env = Environment.GetEnvironmentVariable("LUA_PATH_5_2");
  31. if (!string.IsNullOrEmpty(env)) ModulePaths = UnpackStringPaths(env);
  32. }
  33. if (ModulePaths == null)
  34. {
  35. env = Environment.GetEnvironmentVariable("LUA_PATH");
  36. if (!string.IsNullOrEmpty(env)) ModulePaths = UnpackStringPaths(env);
  37. }
  38. if (ModulePaths == null)
  39. {
  40. ModulePaths = UnpackStringPaths("?;?.lua");
  41. }
  42. }
  43. /// <summary>
  44. /// Resolves the name of a module to a filename (which will later be passed to OpenScriptFile).
  45. /// The resolution happens first on paths included in the LUA_PATH global variable, and -
  46. /// if the variable does not exist - by consulting the
  47. /// ScriptOptions.ModulesPaths array. Override to provide a different behaviour.
  48. /// </summary>
  49. /// <param name="modname">The modname.</param>
  50. /// <param name="globalContext">The global context.</param>
  51. /// <returns></returns>
  52. public override string ResolveModuleName(string modname, Table globalContext)
  53. {
  54. DynValue s = globalContext.RawGet("LUA_PATH");
  55. if (s != null && s.Type == DataType.String)
  56. return ResolveModuleName(modname, UnpackStringPaths(s.String));
  57. else
  58. return base.ResolveModuleName(modname, globalContext);
  59. }
  60. }
  61. }
  62. #endif