在使用带for循环,if语句和while循环的数组时需要帮助

时间:2018-08-03 01:02:54

标签: arrays lua iteration

所以我在创建我认为需要2分钟的努力时遇到了问题。我本人已经学习Java两年了,但是我发现很难将自己学到的一些东西“调整”到LUA。我想创建一个用户名数组,并想完整地检查该数组以在if语句中使用。

这就是我所做的,我绝不会认为它是完整的,因此我希望对此有所帮助。

我愿意完全重写此内容,以便对任何输入和所有输入表示赞赏。

local function main()
    UserNames = {}
    UserNames[1] = "Maximus"
    UserNames[2] = "John"

    print("Enter your Username")
    inputUserName = io.read("*l")

    for i=1,2 do
        --print(v)
        if inputUserName == UserNames[i] then
            print("Username Found")
            print("Welcome", UserNames[i])
            break
        else
            while inputUserName ~= UserNames[i] do
                print("ERROR, Username Doesn't Exist")
                print("Enter your Username")
                inputUserName = io.read("*l")
            end
        end
    end
end
main()

1 个答案:

答案 0 :(得分:0)

您根本不需要进行很多更改,这很可爱!我在这里的Lua文件中保留了一些创造力,并将这些内容分解为一些小段的函数,使您可以更轻松地进行管理。

简而言之,归结为只是遍历数组以触发特定条件,从而退出我们的阵营。像下面这样进行一些调整,您应该具有解决此迭代问题所需的条件。

-- Here's a thought, store these within a separate Lua file and import them using modules!
-- Or better yet, learn a little SQL and make it as secure as you can. :)
UserNames = {};
UserNames[1] = "Maximus";
UserNames[2] = "John";

-- If the username input is contained within UserNames array.
-- Returns: boolean
local function CheckUsername(usernameString)
    for k, v in pairs(UserNames) do
        if (usernameString == v) then
            return true;
        end
    end
    return false;
end

-- Recieve input from the command line. Will wait for completion.
-- Returns: nothing yet.
local function ReceiveUsername()
    local input = nil;
    local matchFound = false;
    local cancelled = false;

    while (matchFound == false and cancelled == false) do

        print("Please, enter your username:");
        input = io.read("*l");

        -- This is probably the most self-explanitory function I've ever written. I'm so happy.
        result = CheckUsername(input);

        if (result == true) then
            matchFound = true;
        end

        if (input == "exit") then
            cancelled = true;
        end

    end

    if (matchFound) then
        print("Welcome, "..input);
    end

    if (cancelled) then
        print("Cancelled the loop.");
    end

    --  Apply more switch cases here. (I wish Lua had switch cases, but you can't win 'em all.)    
    --  Optional: 
    --  Return key, value pair for later iteration.
    --  Make the user a table of values that contains different priviledges. :)
end

local function main()
    -- The main brains of receiving input.
    ReceiveUsername();
end

-- Cache all our functionality before we call main.
main();

功能列表如下:

  • main:现在,只调用ReceiveUsername,什么都没有。 Main最多只能真正调用一两个东西。保持纯净。
  • ReceiveInput:在这里进行迭代。我们先缓存变量,然后说While we aren't cancelling or matching, keep on getting input until we do. Then just use what we have later in the function.
  • CheckUsername:一个简单的辅助函数,用于将字符串与我们的表进行比较。简洁;看看吧。