1

我对在 Lua 函数中使用的 elseif 有疑问。我在 Windows 上使用 LuaEdit 2010,如果是第一个代码,程序会冻结。第二个有效,但非常丑陋,并且如果有更多 elseifs 也非常不可用。我认为它应该在这两种情况下都有效,但它不是,我不知道为什么,请帮助我。Lua Edit 好像功能没有关闭。此代码不起作用

function read_this()
    char=read_char()
    word=""
    if char=="~" then    word = word..char
                        char=read_char()
                        if char == "+" then      
                               formating=true 
                               word=word..char
                        elseif char == "-" then 
                               formating=false
                               word = word..char 
                        else word = word..char
                        end
                    write(word,file2)
    else    print("something what is not problem")
    end                 
end

这段代码对我有用。

function read_this()
    char=read_char()
    word=""
    if char=="~" then    word = word..char
                        char=read_char()
                        if char == "+" or char == "-" then  
                               if char == "+" then formating=true end
                               if char == "-" then formating=false end
                               word = word..char 
                        else word = word..char
                        end
                    write(word,file2)
    else    print("something what is not problem")
    end                 
end
4

1 回答 1

4

这两个例子在我看来在功能上是一样的。我真的会研究你对换行符、空格和缩进的使用,因为你拥有它的方式看起来真的很乱。你的第一个例子我会写成

function read_this()
    char = read_char()
    word = ""
    if char == "~" then
        word = word .. char
        char = read_char()
        if char == "+" then      
            formating = true 
            word = word .. char
        elseif char == "-" then 
            formating = false
            word = word .. char 
        else
            word = word .. char
        end
        write(word,file2)
    else
        print("something what is not problem")
    end                 
end

我还注意到,在每种情况下,您都需要执行 a word = word .. char,因此无需将它放在每个 if 语句中,然后像这样放在它之后:

function read_this()
    char = read_char()
    word = ""
    if char == "~" then
        word = word .. char
        char = read_char()
        if char == "+" then      
            formating = true 
        elseif char == "-" then 
            formating = false 
        end
        word = word .. char
        write(word,file2)
    else
        print("something what is not problem")
    end                 
end
于 2015-03-12T10:26:38.500 回答