0

I know the stdin.read_line() function, but I wanted to make my code less verbose via the use or something more in line to raw_input() in python.

So I found out about GNU ReadLine in this discussion about vala, however I can`t reproduce it in Genie.

The python code that I want to mimic is:

loop = 1
while loop == 1:
    response = raw_input("Enter something or 'quit' to end => ")
    if response == 'quit':
        print 'quitting'
        loop = 0
    else:
        print 'You typed %s' % response

The far I could get was:

[indent=4]

init
    var loop = 1
    while loop == 1
        // print "Enter something or 'quit' to end => "
        var response = ReadLine.read_line("Enter something or 'quit' to end => ")
        if response == "quit"
            print "quitting"
            loop = 0
        else 
            print "You typed %s", response

And tried to compile with:

valac --pkg readline -X -lreadline loopwenquiry.gs 

But I am getting the error:

loopwenquiry.gs:7.24-7.31: error: The name `ReadLine' does not exist in the context of `main'
        var response = ReadLine.read_line("Enter something or 'quit' to end => ")
                       ^^^^^^^^
loopwenquiry.gs:7.22-7.81: error: var declaration not allowed with non-typed initializer
        var response = ReadLine.read_line("Enter something or 'quit' to end => ")
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
loopwenquiry.gs:8.12-8.19: error: The name `response' does not exist in the context of `main'
        if response == "quit"
           ^^^^^^^^
loopwenquiry.gs:12.35-12.42: error: The name `response' does not exist in the context of `main'
            print "You typed %s", response
                                  ^^^^^^^^
Compilation failed: 4 error(s), 0 warning(s)

What am I doing wrong?

Thanks.

4

1 回答 1

1

正如 Jens 的评论中所述,命名空间是 Readline,而不是 ReadLine。该函数也是readline,而不是read_line。所以你的工作代码是:

[indent=4]
init
    while true     
        response:string = Readline.readline("Enter something or 'quit' to end => ")
        if response == "quit"
            print "quitting"
            break
        else
            print "You typed %s", response

我注意到你valac --pkg readline -X -lreadline loopwenquiry.gs用来编译,这很好。-X -lreadline告诉链接器使用库readline。在大多数情况下,您不需要这样做,因为有一个pkg-config文件,这些文件有一个.pc文件扩展名,其中包含所有必要的信息。看起来好像有人已经提交了一个补丁来修复这个到 readline 库。所以使用应该是例外,因为大多数库都有一个文件。-X -llibrary_i_am_using.pc

我还使用while..break了无限循环,看看你是否认为这是一种更清晰的风格。

于 2015-10-05T11:59:49.263 回答