需要注意的是LUA_INIT
(or LUA_INIT_5_3
,...)环境变量:
当没有选项调用时-E
,解释器检查环境变量LUA_INIT_5_3
(or LUA_INIT
如果版本化名称未定义),则在运行任何参数之前。如果变量内容的格式为@filename
, then lua
执行该文件。否则,lua
执行字符串本身。
– https://www.lua.org/manual/5.3/manual.html#7 https://www.lua.org/manual/5.3/manual.html#7
如果您有固定的函数列表,您可以简单地创建一个文件(例如${HOME}/.lua_init.lua
,在 Windows 上也许可以尝试%APPDATA%\something
or %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
that dofile
s or require
根据需要创建 s 文件,定义函数,...
更高级的解决方案(不需要每个文件夹有额外的文件)会更难实现,但您可以运行任意 Lua 代码来构建您需要的任何内容。