title: How to structure internal dependencies in a Lua library?
body: <p>I'm struggling to figure out how to structure and then use internal dependencies in a Lua library I'm writing.</p>
  
  <p>I've defined my library like this:</p>
  
  <pre><code>./alib.lua
  ./alib/adependency.lua
  </code></pre>
  
  <p>And the code:</p>
  
  <pre><code>-- File: ./alib.lua
  local ad = require "alib.adependency"
  module( "alib")
  return {}
  
  -- File: ./alib/adependency.lua
  module( "adependency" )
  return {}
  </code></pre>
  
  <p>This works a treat:</p>
  
  <pre><code>$ lua alib.lua
  &lt;no output&gt;
  </code></pre>
  
  <p>Now let's "add" this library into another app:</p>
  
  <pre><code>./anapp.lua
  ./lib/alib.lua
  ./lib/alib/adependency.lua
  </code></pre>
  
  <p>And the new code:</p>
  
  <pre><code>-- File: ./anapp.lua
  local alib = require "lib.alib"
  local print = print
  module( "anapp")
  print "Hello"
  </code></pre>
  
  <p>Try to run it:</p>
  
  <pre><code>$ lua anapp.lua
  lua: ./lib/alib.lua:2: module 'alib.adependency' not found:
      no field package.preload['alib.adependency']
      no file './alib/adependency.lua'
      no file '/usr/local/share/lua/5.1/alib/adependency.lua'
      no file '/usr/local/share/lua/5.1/alib/adependency/init.lua'
      no file '/usr/local/lib/lua/5.1/alib/adependency.lua'
      no file '/usr/local/lib/lua/5.1/alib/adependency/init.lua'
      no file '/usr/share/lua/5.1/alib/adependency.lua'
      no file '/usr/share/lua/5.1/alib/adependency/init.lua'
      no file './alib/adependency.so'
      no file '/usr/local/lib/lua/5.1/alib/adependency.so'
      no file '/usr/lib/x86_64-linux-gnu/lua/5.1/alib/adependency.so'
      no file '/usr/lib/lua/5.1/alib/adependency.so'
      no file '/usr/local/lib/lua/5.1/loadall.so'
      no file './alib.so'
      no file '/usr/local/lib/lua/5.1/alib.so'
      no file '/usr/lib/x86_64-linux-gnu/lua/5.1/alib.so'
      no file '/usr/lib/lua/5.1/alib.so'
      no file '/usr/local/lib/lua/5.1/loadall.so'
  stack traceback:
      [C]: in function 'require'
      ./lib/alib.lua:2: in main chunk
      [C]: in function 'require'
      anapp.lua:2: in main chunk
      [C]: ?
  </code></pre>
  
  <p>Oh dear. Now I make a manual edit inside the library:</p>
  
  <pre><code>-- File: ./lib/alib.lua
  -- local ad = require "alib.adependency" -- Doesn't work
  local ad = require "lib.alib.adependency" -- Works
  module( "alib")
  return {}
  </code></pre>
  
  <p>And it works:</p>
  
  <pre><code>$ lua anapp.lua
  Hello
  </code></pre>
  
  <p>It seems that Lua's <code>require()</code> relates paths relative to the ultimate script being run by Lua, not the script in which the <code>require()</code> is called.</p>
  
  <p>Surely you don't have to manually fix the internal paths <code>require()</code>d inside of a Lua library every time you add one to your project... And I don't see how this can work from a unit test perspective either. What am I doing wrong?</p>