【问题标题】:How to create new commands in the Lua interpreter如何在 Lua 解释器中创建新命令
【发布时间】:2017-01-29 00:46:17
【问题描述】:

编辑:我在 ubuntu 上

因此,在 lua 解释器中,您显然可以调用内置函数,例如

> 函数名(函数参数)

我想创建一个新函数,每次输入时 lua 解释器都能识别它。

有没有一种方法可以将我的函数添加到 lua 解释器中本机识别的函数列表中,这样我就不必在写入它的文件上调用 dofile() 然后从那里运行它。

TLDR我希望能够打字

> myNewFunction(functionArgs)

随时在lua解释器中,让解释器自动知道我在说什么函数。

如果这是不可能的,至少有一种方法可以让我在任何目录中运行 dofile(myFile) 并且 lua 解释器总是能够找到包含我的函数的特定文件?

感谢您的帮助!

【问题讨论】:

    标签: lua


    【解决方案1】:

    要看的是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 代码来构建您需要的任何东西。

    【讨论】:

    • 在Windows上:控制面板->系统->高级->环境变量->按钮“新建”->设置变量名LUA_INIT和变量值@%USERPROFILE%\auto load.lua,按“确定”按钮,然后编辑您的文件notepad "%USERPROFILE%\auto load.lua" 并保存。现在打开 fresh Windows 控制台窗口(已经打开的控制台窗口将看不到您的新环境变量)并运行lua.exe。您的文件 auto load.lua 已经加载到 Lua 中,并且其中定义的所有函数都可用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-25
    • 2014-03-10
    • 2011-04-08
    相关资源
    最近更新 更多