2014-09-05 26 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上)。