getch FFI example: nldecl version
##[[
local nldecl = require 'nelua.plugins.nldecl'
local fs = require 'nelua.utils.fs'
if not fs.isfile('termios-bindings.nelua') then
nldecl.generate_bindings_file {
output_file = 'termios-bindings.nelua',
parse_includes = {'<termios.h>', '<unistd.h>', '<pcre.h>', '<stdio.h>'},
typedefs = 'termios',
include_names = {'attr$', '^termios$', '^getchar$', 'ICANON', 'ECHO', 'TCSANOW'},
}
end
cinclude '<termios.h>'
cinclude '<unistd.h>'
]]
require 'termios-bindings'
local function getch(): uint8
local oldattr: termios <noinit>
local newattr: termios <noinit>
tcgetattr(0, &oldattr)
newattr = oldattr
newattr.c_lflag = newattr.c_lflag & ~(ICANON | ECHO)
tcsetattr(0, TCSANOW, &newattr)
local ch = getchar()
tcsetattr(0, TCSANOW, &oldattr)
return ch
end
print('Press a key:')
local c = getch()
print('I read:', c)Resulting in this file:
global termios: type <cimport,nodecl,ctypedef'termios'> = @record{
c_iflag: cuint,
c_oflag: cuint,
c_cflag: cuint,
c_lflag: cuint,
c_line: cuchar,
c_cc: [32]cuchar,
c_ispeed: cuint,
c_ospeed: cuint
}
global function tcgetattr(fd: cint, termios_p: *termios): cint <cimport,nodecl> end
global function tcsetattr(fd: cint, optional_actions: cint, termios_p: *termios): cint <cimport,nodecl> end
global function getchar(): cint <cimport,nodecl> end
global ICANON: cint <comptime> = 2
global ECHO: cint <comptime> = 8
global ECHOE: cint <comptime> = 16
global ECHOK: cint <comptime> = 32
global ECHONL: cint <comptime> = 64
global ECHOCTL: cint <comptime> = 512
global ECHOPRT: cint <comptime> = 1024
global ECHOKE: cint <comptime> = 2048
global TCSANOW: cint <comptime> = 0