Search code examples
luascopepackagelua-5.3

Lua: Local package.path


In Lua is there a way to define package.path to apply only to a local scope?

I understand I could store the package.path in a local variable and restore it before my script ends as in the example below but is there a cleaner way?

local startingPackagePath = package.path
package.path = "../Lib/?.lua;" .. package.path
local someLib = require "someLib"
package.path = startingPackagePath
--Do some stuff

Solution

  • I don't think there is a shorter way to make package.path module-specific, but you may consider using package.preload that allows to provide a custom loader, which may look at module-specific path.