Frage

I need help turning off this feature if possible from the interactive mode or I'm going to go mad. The REPL insists on an equal sign before every expression if you want the value. I find this very irritating and unintuitive. To make matters worse, if you mistakenly forget the equal sign, it takes you to this secondary prompt which can only be exited by typing an expression that'll cause an error.

*** 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
*** 

I need a lesson in using the REPL:
Is there a way to get rid of the equal sign so that it behaves like other REPLs?
How do you exit from the secondary prompt without doing what I did?

War es hilfreich?

Lösung

Everything you enter in standalone Lua is treated as a statement, as opposed to an expression. The statements are evaluated, and their results, if any, are printed to the terminal. This is why you need to prepend = (really shorthand for return) to the expressions you gave as example to get them to display properly without error.

The "secondary prompt" you are seeing is what happens when you enter an incomplete statement.

In interactive mode, if you write an incomplete statement, the interpreter waits for its completion by issuing a different prompt.

You exit from it by completing the statement.


However, it's not too difficult to make your own REPL that does what you want. Of course, you lose the ability to progressively build statements from incomplete chunks this way, but maybe you don't need that.

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

Andere Tipps

Since Lua 5.3, you don't need the =, because Lua first tries to interpret it as an expression now.

From the reference manual:

In interactive mode, Lua repeatedly prompts and waits for a line. After reading a line, Lua first try to interpret the line as an expression. If it succeeds, it prints its value. Otherwise, it interprets the line as a statement. If you write an incomplete statement, the interpreter waits for its completion by issuing a different prompt.

A little test:

Lua 5.3.0  Copyright (C) 1994-2014 Lua.org, PUC-Rio
> str = 'hello' .. ' Lua'
> str
hello Lua
> 1 + 2
3
> 
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top