Hide password with an asterisk in lua

I have a way to set a password in lua, but hide with asterisks?

I'm asking about a console application

+4
source share
2 answers

For Unix: use os.execute("stty -echo raw") to disable the echo and enter raw mode (character input) and os.execute("stty echo cooked") to enable it and exit raw mode, when you are done. In raw mode, you can get each input character using io.stdin:read(1) and repeat the asterisk during the game (use io.flush to make sure the character appears immediately). You will need to handle the deletion and the end of the line yourself.

For Windows, the situation is a little more complicated. See What is the Windows Package Equivalent for HTML = "Password" Input Type? for some approaches, the best of which is a VB script.

Postscript

Thank you for lhf for the fact that you need a raw mode besides -echo at the input and reset after each output asterisk to get the desired result: if you do not have both, asterisks will not be displayed until the line ends.

+5
source

This code uses platform-specific features and works on both Linux and 32-bit Windows.
Compatible with Lua 5.1 and Lua 5.2

 local console local function enter_password(prompt_message, asterisk_char, max_length) -- returns password string -- "Enter" key finishes the password -- "Backspace" key undoes last entered character if not console then if (os.getenv'os' or ''):lower():find'windows' then ------------------ Windows ------------------ local shift = 10 -- Create executable file which returns (getch()+shift) as exit code local getch_filespec = 'getch.com' -- mov AH,8 -- int 21h -- add AL,shift -- mov AH,4Ch -- int 21h local file = assert(io.open(getch_filespec, 'wb')) file:write(string.char(0xB4,8,0xCD,0x21,4,shift,0xB4,0x4C,0xCD,0x21)) file:close() console = { wait_key = function() local code_Lua51, _, code_Lua52 = os.execute(getch_filespec) local code = (code_Lua52 or code_Lua51) - shift assert(code >= 0, getch_filespec..' execution failed') return string.char(code) end, on_start = function() end, on_finish = function() end, backspace_key = '\b' } ------------------------------------------- else ------------------ Linux ------------------ console = { wait_key = function() return io.read(1) end, on_start = function() os.execute'stty -echo raw' end, on_finish = function() os.execute'stty sane' end, backspace_key = '\127' } ------------------------------------------- end end io.write(prompt_message or '') io.flush() local pwd = '' console.on_start() repeat local c = console.wait_key() if c == console.backspace_key then if #pwd > 0 then io.write'\b \b' pwd = pwd:sub(1, -2) end elseif c ~= '\r' and #pwd < (max_length or 32) then io.write(asterisk_char or '*') pwd = pwd..c end io.flush() until c == '\r' console.on_finish() io.write'\n' io.flush() return pwd end -- Usage example local pwd = enter_password'Enter password: ' print('You entered: '..pwd:gsub('%c','?')) print(pwd:byte(1,-1)) 
+2
source

All Articles