LUA。有时间限制io.read [英] LUA. io.read with time limit

查看:320
本文介绍了LUA。有时间限制io.read的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就可以设定时限的阅读终端输入在Lua。

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

例如,你HABE仅需1秒钟写信其他程序跳过此动作。

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

感谢任何提示;)

推荐答案

您可以通过更改终端设置做到这一点(见的 男人使用的termios luaposix (POSIX上唯一的机器,显然):

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 )

这篇关于LUA。有时间限制io.read的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆