Surge12
Surge12

Reputation: 335

How can I make a password system in Lua?

I am trying to make a password system, but for some reason, the code I want it to run when the password is correct doesn't run. I am not sure what is wrong, but I am looking for a solution to the problem, or another way to simply make a password system. Here is what I have:

term.setTextColor( colors.red )
print("Password Required")
term.setTextColor( colors.cyan )
io.write("Password:")
local password = io.read()

while (password ~= "Password") do

    io.write("Incorrect")
    print("")
    io.write("Password:")
    password = io.read()
    if password=="Password" then
        sleep(.5)
        term.setTextColor( colors.green )
        print("Access Granted")
    end
end

Upvotes: 0

Views: 3892

Answers (1)

ATaco
ATaco

Reputation: 486

A basic solution to this problem can be achieved with a while loop.

term.setTextColor( colors.red )
print("Password Reqired")

while true do
    term.setTextColor(colors.cyan)
    io.write("Password:\t")
    term.setTextColor(colors.white)
    password = io.read()
    if password=="Password" then
        sleep(.5)
        term.setTextColor(colors.green)
        print("Access Granted")
        break
    else
        term.setTextColor(colors.red)
        print("Access Denied")
    end
end

This constantly repeats itself until the correctly answered password is supplied, in which break escapes the loop.

However, judging by your calls to 'term', I'm assuming you're using ComputerCraft. If so, you probably also want to prevent terminating, which can be done by overwriting the error function.

term.setTextColor( colors.red )
print("Password Reqired")


function error(txt)
    term.setTextColor(colors.red)
    print(txt)
end

while true do
    term.setTextColor(colors.cyan)
    io.write("Password:\t")
    term.setTextColor(colors.white)
    password = io.read()
    if password=="Password" then
        sleep(.5)
        term.setTextColor(colors.green)
        print("Access Granted")
        break
    else
        term.setTextColor(colors.red)
        print("Access Denied")
    end
end

But note, if someone can place a disk drive next to your computer, they can still get in.

Upvotes: 1

Related Questions