为什么Lua REPL要求你在前面添加一个等号以获得一个值?

Seg*_*ult 10 lua read-eval-print-loop

我需要帮助关闭此功能,如果可能的话,从交互模式或我会发疯.如果你想要这个值,REPL会在每个表达式之前坚持等号.我发现这非常刺激和不直观.更糟糕的是,如果你错误地忘记了等号,它会带你进入这个辅助提示,只有输入一个会导致错误的表达式才能退出.

*** str="This is some string"
*** str
>>
>>
>> =
>>
>> =str
stdin:6: unexpected symbol near '='
*** =str
This is some string
*** #str
stdin:1: unexpected symbol near '#'
*** =#str
19
***
*** 545+8
stdin:1: unexpected symbol near '545'
*** =545+8
553
*** 
Run Code Online (Sandbox Code Playgroud)

我需要一个使用REPL的教训:
有没有办法摆脱等号,这样它的行为就像其他REPL一样?
如果不做我做的事情,你如何退出辅助提示?

Rya*_*ein 9

您在独立Lua中输入的所有内容都被视为语句,而不是表达式.评估报表,并将其结果(如果有的话)打印到终端.这就是为什么你需要在你给出的表达式前加上=(真正的简写 return),以使它们正确显示而不会出错.

您看到的"辅助提示"是输入不完整语句时发生的情况.

在交互模式下,如果编写不完整的语句,解释程序将通过发出不同的提示来等待其完成.

您可以通过填写语句退出它.


但是,制作自己的REPL并不是很难做到你想要的.当然,你失去了以这种方式从不完整的块中逐步构建语句的能力,但也许你不需要它.

local function print_results(...)
    -- This function takes care of nils at the end of results and such.
    if select('#', ...) > 1 then
        print(select(2, ...))
    end
end

repeat -- REPL
    io.write'> '
    io.stdout:flush()
    local s = io.read()
    if s == 'exit' then break end

    local f, err = load(s, 'stdin')
    if err then -- Maybe it's an expression.
        -- This is a bad hack, but it might work well enough.
        f = load('return (' .. s .. ')', 'stdin')
    end

    if f then
        print_results(pcall(f))
    else
        print(err)
    end
until false
Run Code Online (Sandbox Code Playgroud)

  • @Segfault在Lua 5.2中,使用`load`; 在Lua 5.1中,使用`loadstring`.你可能正在使用Lua 5.1 (3认同)

Yu *_*Hao 5

从Lua 5.3开始,你不需要=,因为Lua现在首先尝试将其解释为表达式.

参考手册:

在交互模式下,Lua反复提示并等待一条线.读完一行后,Lua首先尝试将该行解释为表达式.如果成功,则打印其值.否则,它将该行解释为语句.如果您编写了不完整的语句,则解释程序会通过发出不同的提示来等待其完成.

一点测试:

Lua 5.3.0  Copyright (C) 1994-2014 Lua.org, PUC-Rio
> str = 'hello' .. ' Lua'
> str
hello Lua
> 1 + 2
3
> 
Run Code Online (Sandbox Code Playgroud)