[luau] C program question

Ray Strode halfline at hawaii.rr.com
Thu May 23 03:26:00 PDT 2002


> 	I'm wrestling with a little program....  What I want is for the program to 
> "pause" for a moment when it is done with output until the user presses a 
> key. Then it should continue.   What I thought should work is this:
By default the console is in what's called cooked mode.  It means it's
buffered until it encounters eol.  What you want to do is put it in
rawmode.  You can do that two ways...one simple way to do that is to use
termios.  Example:

#include <termios.h>
#include <stdio.h>
void wait_for_key() {

    /*
     * Allocate two structures on the stack.
     * The first is to maintain state long enough 
     * to put the console in "raw" mode.  And the
     * second is used to bring it back to the 
     * mode it was originally in.
     */
    struct termios rawmode = {0}, savemode = {0};

    /*
     * Save current console state
     */
    tcgetattr(fileno(stdin), &savemode);

    /*
     * Get the state information necessary to go 
     * into raw mode
     */
    cfmakeraw(&rawmode);

    /*
     * Use that state information to go in to 
     * raw mode.
     */
    tcsetattr(fileno(stdin), 0, &rawmode);

    /*
     * Wait for a key...
     */
    getchar();

    /*
     * Restore original console state
     */
    tcsetattr(fileno(stdin), 0, &savemode);
}

I noticed you are using curses.  If this is 
because you found getch() in a man page and
remembered getch() from Borland C++'s 
conio.h, then don't use curses, instead use 
the above method.  If you are planning on
using cursors to make nice text dialogs 
and such, then read on.

curses must first be initialized before it can
be used.  To do that, call initscr().  Note
this will also make the screen clear, so you
probably want to do it at the beginning of your
program.  Then you still have to put the console 
in raw mode, but curses has a function for that,
cbreak().  To return to cooked mode use nocbreak().
Here's an example:

#include <curses.h>
void wait_for_key() {
    static int run_before = 0;

    if (!run_before) {

        /*
         * Note the screen will be cleared, so
         * this would be better to call at the
         * beginning of program instead of in 
         * this function.
         */
        initscr();  
        run_before = 1;
    }

    /*
     * Go into raw mode
     */
    cbreak();

    /*
     * Wait for a key ...
     */
    getch();

    /*
     * Go into cooked mode
     */
    nocbreak();
}

Note the above example needs -lcurses added to the link line of
the compiler.

If you want to write cool looking programs that work on a wide variety
of terminal types, curses is the way to go.  If you want something 
simple that is very low hassle use termios.

--Ray




More information about the LUAU mailing list