2014-09-05 61 views

回答

2

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

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

的lcurses(ncurses的为lua)的Lua库可能提供这一点。你将不得不下载并安装它。有一个例子,如何检查按键只在Create a function to check for key press in unix using ncurses,它是在C中,但在Lua中的ncurses API是相同的。否则,你将不得不使用C/C++ API创建一个Lua扩展模块:你将创建你从Lua调用的C函数,然后这个C函数可以访问操作系统通常的函数,比如getch,select,等等(取决于你是否在Windows或Linux上)。