How are modules Loaded

  • On the first require statement for a module
    • Lua searches for the Lua file with the module name
    • If it finds a Lua file it calls "loadfile" which gives a loader for the file
    • If it cannot find a Lua file it looks for a C library with the name
    • If a C file is found it calls package.loadlib which gives a loader for the file
    • Require now calls the loader to load the module
    • Require returns the return value from the loader and puts it into the package.loaded table
    • Upon subsequent calls to require the package.loaded file has the reference to the module

Path Searching

  • Lua uses a set of templates to search for modules rather than a set of paths

    • Each template is a path with optional question marks (?)
    • The templates in a path are separated by semicolons
    • The question marks are replaced by the module name given to require
  • The path for finding Lua files comes from variable package.path

    • Package.path is loaded when Lua starts up from LUA_PATH
      • LUA_PATH is in the environment variables of the operating system
      • If this cannot be found Lua uses a default path
  • The path for finding C files comes from variable package.cpath
    • package.cpath comes from environment variable LUA_CPATH

Module Search Path in Package Table