为什么Lua中的if-elseif-else语句不能正常工作?

时间:2015-03-12 10:05:04

标签: function if-statement lua freeze lua-edit

我遇到了elseif的问题,它在Lua函数中使用。我在Windows上使用LuaEdit 2010,如果是第一个代码,程序会冻结。第二个工作,但非常丑陋,并且更多的其他也很不可用。我认为这应该适用于两种情况,但不是,我不知道为什么,请帮助我。 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

1 个答案:

答案 0 :(得分: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

我还注意到,在每种情况下你都会做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