要看的是LUA_INIT(或LUA_INIT_5_3,...)环境变量:
在不带选项 -E 的情况下调用时,解释器会在运行任何参数之前检查环境变量 LUA_INIT_5_3(或 LUA_INIT,如果未定义版本名称)。如果变量内容的格式为@filename,则lua 执行该文件。否则,lua 会自行执行字符串。
– https://www.lua.org/manual/5.3/manual.html#7
如果你有一个固定的函数列表,你可以简单地创建一个文件(例如${HOME}/.lua_init.lua,在 Windows 上可以尝试%APPDATA%\something 或%USERPROFILE%\something。)然后,将你的函数放入该文件并设置其中一个LUA_INIT 指向该文件的环境变量,以“@”作为文件路径的前缀。 unixoid OSen 的小例子:
$ cd # just to ensure that we are in ${HOME}
$ echo "function ping( ) print 'pong' end" >> .lua_init.lua
$ echo 'export LUA_INIT="@${HOME}/.lua_init.lua"' >> .profile
$ source .profile
$ lua
Lua 5.3.3 Copyright (C) 1994-2016 Lua.org, PUC-Rio
> ping()
pong
(对于 Windows,请参阅下面 Egor Skriptunoff 的评论。)
如果你想从当前目录自动加载东西,那就更难了。一种简单的方法是设置上述内容,然后添加例如
-- autoload '.autoload.lua' in current directory if present
if io.open( ".autoload.lua" ) then -- exists, run it
-- use pcall so we don't brick the interpreter if the
-- file contains an error but can continue anyway
local ok, err = pcall( dofile, ".autoload.lua" )
if not ok then print( "AUTOLOAD ERROR: ", err ) end
end
-- GAPING SECURITY HOLE WARNING: automatically running a file
-- with the right name in any folder could run untrusted code.
-- If you actually use this, add a whitelist of known-good
-- project directories or at the very least blacklist your
-- downloads folder, /tmp, and whatever else might end up
-- containing a file with the right name but not written by you.
进入LUA_INIT 文件。然后,要自动加载特定于项目/目录的函数,请创建一个 .autoload.lua,根据需要创建 dofiles 或 requires 文件,定义函数,...
更高级的解决方案(不需要每个文件夹额外的文件)将更难实现,但您可以运行任意 Lua 代码来构建您需要的任何东西。