lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Am 23.09.2015 um 14:58 schröbte Dirk Laurie:
In a program, one can say

mymod = require "mymod"

or

mymod = dofile "mymod.lua"

Is there any way that the code of "mymod.lua" can distinguish
between these?

If `mymod.lua` has access to the debug module, it can search the stack for the nearest `require`/`dofile` function:

    local function detect()
      local i = 3
      local info = debug.getinfo( i, "f" )
      while info do
        if info.func == require then
          return "require"
        elseif info.func == dofile then
          return "dofile"
        end
        i = i + 1
        info = debug.getinfo( i, "f" )
      end
      return "other"
    end

    print( detect() )

Results:
    $ lua -i mymod.lua
    Lua 5.2.3  Copyright (C) 1994-2013 Lua.org, PUC-Rio
    other
    > require( "mymod" )
    require
    > dofile( "mymod.lua" )
    dofile
    > loadfile( "mymod.lua" )()
    other
    >

Philipp