Keyboard input/Obtain a Y or N response: Difference between revisions
Content added Content deleted
(Category:Keyboard Input -> Category:Keyboard input lowercase "input") |
(more documentation plus some code prettifying) |
||
Line 1,332: | Line 1,332: | ||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
Unix |
<code>Unix</code> module, exposing POSIX interfaces like [https://en.wikipedia.org/wiki/POSIX_terminal_interface termios], is normally bundled with any standard OCaml distribution. Utilizing termios is the solution many other language examples here went with. |
||
Interfacing with [https://en.wikipedia.org/wiki/POSIX_terminal_interface termios] is specific to UNIX-likes. |
|||
OCaml needs to link to the bundled unix archives correctly in order to compile / run code that uses definitions within the module. To do this with the plain OCaml toolchain, remember to add the library archive to the commandline like so: |
|||
⚫ | |||
type mode = Prompt | Input |
|||
let original_attrs = tcgetattr stdin |
|||
let set = function |
|||
| Prompt -> tcsetattr stdin TCSAFLUSH {original_attrs with c_icanon = false} |
|||
⚫ | |||
⚫ | |||
⚫ | |||
else Bytes.get buf 0</lang> |
|||
<code>ocaml unix.cma <yourfile.ml></code> interpreted<br/> |
|||
Main: |
|||
<code>ocamlc -o <progname> unix.cma <yourfile.ml></code> bytecode executable<br/> |
|||
<lang OCaml>let _main = |
|||
<code>ocamlopt -o <progname> unix.cmxa <yourfile.ml></code> native executable |
|||
⚫ | |||
⚫ | |||
Here we define some helper functions that we'll use: |
|||
⚫ | |||
flush_all(); |
|||
<lang OCaml>let attrs = Unix.(tcgetattr stdin) |
|||
set Prompt; |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
@@ if switch then { attrs with c_icanon = false } else attrs |
|||
set Input; |
|||
in |
|||
⚫ | |||
prompt ()</lang> |
|||
let len = Unix.(read stdin) buf 0 1 in |
|||
⚫ | |||
Now the main program: |
|||
⚫ | |||
⚫ | |||
loop |
|||
@@ print_endline |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
let _ = try loop @@ prompt true with Exit | End_of_file -> prompt false</lang> |
|||
=={{header|Oforth}}== |
=={{header|Oforth}}== |