简体   繁体   中英

LUA. io.read with time limit

it is possible set time limit to read input in terminal in Lua.

For example you habe only 1 second to write a letter else program skip this action.

thanks for any tip ;)

You can do this by changing the terminal settings (see man termios ) using luaposix (on POSIX machines only, obviously):

local p = require( "posix" )

local function table_copy( t )
  local copy = {}
  for k,v in pairs( t ) do
    if type( v ) == "table" then
      copy[ k ] = table_copy( v )
    else
      copy[ k ] = v
    end
  end
  return copy
end

assert( p.isatty( p.STDIN_FILENO ), "stdin not a terminal" )

-- derive modified terminal settings from current settings
local saved_tcattr = assert( p.tcgetattr( p.STDIN_FILENO ) )
local raw_tcattr = table_copy( saved_tcattr )
raw_tcattr.lflag = bit32.band( raw_tcattr.lflag, bit32.bnot( p.ICANON ) )
raw_tcattr.cc[ p.VMIN ] = 0
raw_tcattr.cc[ p.VTIME ] = 10 -- in tenth of a second

-- restore terminal settings in case of unexpected error
local guard = setmetatable( {}, { __gc = function()
  p.tcsetattr( p.STDIN_FILENO, p.TCSANOW, saved_tcattr )
end } )

local function read1sec()
  assert( p.tcsetattr( p.STDIN_FILENO, p.TCSANOW, raw_tcattr ) )
  local c = io.read( 1 )
  assert( p.tcsetattr( p.STDIN_FILENO, p.TCSANOW, saved_tcattr ) )
  return c
end

local c = read1sec()
print( "key pressed:", c )

The lcurses (ncurses for Lua) Lua library might provide this. You would have to download and install it. There is an example of how to check for keypress only at Create a function to check for key press in unix using ncurses , it is in C but the ncurses API is identical in Lua.

Otherwise, you will have to create a Lua extension module using the C/C++ API: you would create C function that you call from Lua, and this C function then has access to the OS's usual function like getch, select, etc (depends if you are on Windows or Linux).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM