LUA中设置有时间限制的io.read功能。

在 Lua 终端中,可以设置输入读取的时间限制。

例如,你只有 1 秒钟来写一封信,否则程序会跳过这个操作。

感谢任何提示 ?

点赞
用户869951
用户869951

lcurses(针对 Lua 的 ncurses)Lua 库可能提供这个功能。您需要下载并安装它。在创建一个使用 ncurses 在 unix 中检查按键的函数中有一个示例,它使用 C 语言编写,但 ncurses API 在 Lua 中也是相同的。

否则,您将不得不使用 C/C++ API 创建一个 Lua 扩展模块:创建一个 C 函数,然后从 Lua 中调用它,这个 C 函数然后可以访问操作系统的通常函数,如 getch,select 等(这取决于您是在 Windows 还是 Linux 上)。

2014-09-05 16:45:03
用户3677376
用户3677376

你可以通过改变终端设置(参见man termios)使用 luaposix (仅在 POSIX 设备上有效):

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" )

-- 从当前设置推导出修改后的终端设置
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 -- 十分之一秒

-- 在意外错误发生时恢复终端设置
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( "按下的键:", c )
2014-09-08 04:59:03