示例工程 19-modules-and-env

19-modules-and-env/02-custom-package-path/main.lua

lua · 0.7 KB

-- @runtimes lua54 luajit
--- 演示:临时修改 package.path 加载同目录模块。
local M = {}
 
--- @return table { message = string, restored = boolean }
function M.run(log)
	log = log or print
	local original = package.path
	local directory = arg and arg[0] and arg[0]:match("^(.*)/[^/]+$") or "."
	package.path = directory .. "/?.lua;" .. original
	local ok, module = pcall(require, "greet")
	package.path = original
	assert(ok, module)
	log(("message=%s restored=%s"):format(module.hello("Ada"), tostring(package.path == original)))
	return { message = module.hello("Ada"), restored = package.path == original }
end
 
if not ... then
	M.run()
end
return M