I would like to mimic the default way of hiding a password on Ubuntu (for example, when using a sudo command), preferably in Lua 5.1.
2 Answers
I don't know the Ubuntu way, but try this:
io.write("password: ")
io.flush()
os.execute("stty -echo")
password=io.read()
os.execute("stty echo")
2 Comments
vekat
Thank you, I guess this a way to do it.
Etan Reisner
Only thing worth knowing here is that should this get interrupted between the two calls to
stty the terminal will stay in -echo mode (which might confuse someone).#!/usr/bin/env lua
query = "Enter password: "
valid_chars="[%d%w%p]"
io.write(query)
pwd = ''
length = 0
invalid = {}
os.execute("stty -icanon -echo")
while true do
local char = io.read(1)
if char == '\n' or string.byte(char) == 27 then --esc
break
elseif char == '\b' or string.byte(char) == 127 then
if length > 0 then
io.write('\r' .. string.rep(' ', (string.len(query) + length))) -- clear whole line
length = length - 1
pwd = string.sub(pwd, 1, length)
io.write('\r' .. query .. string.rep('*', length))
end
elseif string.match(char, valid_chars) then
pwd = pwd .. char
length = length + 1
io.write('\r' .. query .. string.rep('*', length))
else
table.insert(invalid, char)
end
end
os.execute("stty icanon echo")
if #invalid > 0 then
print("\nThe following characters are not allowed: '" .. table.concat(invalid, "', '") .. "'")
print("The password is invalid!")
else
print("\nPassword is: " .. pwd)
end
1 Comment
Community
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.