如何在 Lua 解释器中创建新命令

编辑:我使用的是Ubuntu操作系统

在 Lua 解释器中,你可以调用内置函数,如:

> functionName(functionArgs)

我想创建一个新函数,使其可以在我输入它时被 Lua 解释器识别。

有没有办法将我的函数添加到 Lua 解释器本地识别的函数列表中,这样我就不必在我编写函数所在的文件上调用 dofile() ,然后从那里运行它。

TLDR我想随时在 Lua 解释器中输入

> myNewFunction(functionArgs)

并且解释器自动知道我在谈论什么函数。

如果不可能的话,是否有一种办法可以在任何目录下运行 dofile(myFile),并且 Lua 解释器总是能够找到包含我的函数的特定文件?

感谢任何帮助!

点赞
用户805875
用户805875

需要注意的是 LUA_INIT(或 LUA_INIT_5_3,...)环境变量:

在没有使用 -E 选项的情况下,解释器在运行任何参数之前会检查环境变量 LUA_INIT_5_3(如果版本名称未定义,则为 LUA_INIT)。如果变量内容的格式为 @filename,则 lua 会执行该文件。否则,lua 执行该字符串本身。

如果你有一个固定的函数列表,你可以简单地创建一个文件(例如 ${HOME}/.lua_init.lua,在 Windows 上可能尝试 %APPDATA%\something%USERPROFILE%\something),然后将你的函数放在该文件中,并设置其中一个指向该文件的 LUA_INIT 环境变量,在文件路径前加上@。下面是 Unixoid 操作系统的简单示例:

$ 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,其中 dofilerequire 必要的文件,定义函数等。

更高级的解决方案(不需要每个文件夹额外的文件)将更难实现,但是你可以运行任意 Lua 代码来构建所需的内容。

2017-01-29 02:12:00