Windows Console Lua

Snakes In A Game!

ConsoleLua is a simple game engine for making character-mode games reminescent of the kinds of things one would write in QBasic on a DOS-based PC in the early 1980s.

It uses Lua 5.1.5 as its scripting system, and adds the Bit Operations library, custom bindings for the Windows Console API, and event hooks for user-supplied event callbacks. It also removes the Lua io and os libraries to "sandbox" the script, though that might not be as good an idea here as it was in the Battlezone mission script framework...

Downloads

Executable (requires the Visual C++ 2013 Redistributable Package)
Source Code (warning: it's not well-documented at all)

Usage

Run the executable with the name of a script file on the command line. For example:

ConsoleLua.exe snake.lua

The executable passes any additional command line arguments to the script as strings. The Lua script can retrieve them with the ... operator.

The application currently does not support interactive mode or command-line script code.

Examples

snake.lua is a port of a simple "snake" game I originally wrote in C++.

Events

In response to various events, the application calls user-supplied event handler functions.

This setup was based on the Lua mission scripting framework I made for the Battlezone unofficial 1.5 patch and was inspired by Processing, p5.js, and LÖVE.

Update ()

Called once per iteration of the main loop.

Remarks

The application (currently) makes no attempt to throttle execution speed so the script should use Sleep function to slow execution to a playable rate.

KeyPressed ( integer repeat, integer keycode, integer scancode, string ascii, integer control )

Called whenever a key is pressed.

Parameters

Remarks

Enhanced keys for the IBM® 101- and 102-key keyboards are the INS, DEL, HOME, END, PAGE UP, PAGE DOWN, and direction keys in the clusters to the left of the keypad; and the divide (/) and ENTER keys in the keypad.

Keyboard input events are generated when any key, including control keys, is pressed or released. However, the ALT key when pressed and released without combining with another character, has special meaning to the system and is not passed through to the application. Also, the CTRL+C key combination is not passed through if the input handle is in processed mode (ENABLE_PROCESSED_INPUT).

KeyReleased ( integer repeat, integer keycode, integer scancode, string ascii, integer control )

Called whenever a key is released.

MouseMoved ( integer x, integer y )

Called whenever the mouse moves.

Parameters

MousePressed ( integer button )

Called whenever a mouse button is pressed.

Parameters

MouseReleased ( integer button )

Called whenever a mouse button is released.

Parameters

MouseWheel ( integer move )

Called whenever the mouse wheel is moved.

Parameters

BufferSize ( integer width, integer height )

Called whenever the console screen buffer changes size.

Parameters

Remarks

Buffer size events are placed in the input buffer when the console is in window-aware mode (ENABLE_WINDOW_INPUT).

SetFocus ( boolean focus )

Called whenever the console window gains or loses focus.

Parameters

Data Types

Handle

A Handle is an opaque reference to a console input or output.

The system provides two global handles:

CreateScreenBuffer is the only way to create additional console screen buffer handles.

Formats

Char

A Char is a single ASCII character.

Formats

Attribute

An Attribute is a foreground color index in the lower 4 bits bits and a background color index in the upper 4 bits of a single byte.

Formats

Coord

A Coord is a position consisting of X (column) and Y (row) values.

Formats

Rect

A Rect is an inclusive rectangular region consisting of Left, Top, Right, and Bottom values.

Formats

CharInfo

A CharInfo is a tuple consisting of a Char and an Attribute.

Formats

CharInfoBuffer

A CharInfoBuffer is a rectangular array of CharInfo. Its size is set at creation and cannot be changed.

NewCharInfoBuffer() is the only way to create a new CharInfoBuffer.

Formats

string Get ( Coord position )

Get the CharInfo at the specified position as a two-character string.

Set ( Coord position, CharInfo value )

Set the CharInfo at the specified position to the specified value.

Color

A Color is a single color consisting of Red, Green, and Blue values.

Formats

Functions

Quit ()

Quit the application.

Pause ( boolean pause )

Pause or resume execution.

Parameters

Sleep ( integer duration )

Suspend execution for the given duration in millseconds.

Parameters

integer GetMillis ()

Get the elapsed time in milliseconds since the application started.

Return Value

The function returns an integer representing elapsed milliseconds.

string GetLastError ()

Get the most recent error message, if any.

Return Value

If an error has been reported, the return value is a string containing the most recent error message. Otherwise, the return value is nil.

CharInfoBuffer NewCharInfoBuffer ( Coord size, CharInfo fill )

Create a new character info buffer with the given size and filled with the given fill value.

Parameters

Remarks

The buffer's size cannot be changed after creation.

Rect ReadOutput( Handle h, CharInfoBuffer buffer, Coord buffer_coord, Rect region )

Reads character and attribute data from a rectangular block of character cells in a console screen buffer and writes the data to a rectangular block at a specified location in the destination buffer.

Parameters

Return value

If the function succeeds, the return value is the region rectangle actually used. Otherwise, the return value is nil.

Remarks

This function treats the console screen buffer and the destination buffer as two-dimensional arrays (columns and rows of character cells). The region rectangle specifies the size and location of the block to be read from the console screen buffer. A destination rectangle of the same size is located with its upper-left cell at the coordinates of the buffer_coord parameter in the buffer. Data read from the cells in the console screen buffer source rectangle is copied to the corresponding cells in the destination buffer. If the corresponding cell is outside the boundaries of the destination buffer rectangle, the data is not copied.

Cells in the destination buffer corresponding to coordinates that are not within the boundaries of the console screen buffer are left unchanged. In other words, these are the cells for which no screen buffer data is available to be read.

Rect WriteOutput( Handle h, CharInfoBuffer buffer, Coord buffer_coord, Rect region )

Writes character and attribute data to a specified rectangular block of character cells in a console screen buffer. The data to be written is taken from a correspondingly sized rectangular block at a specified location in the source buffer.

Parameters

Return value

If the function succeeds, the return value is the region rectangle actually used. Otherwise, the return value is nil.

Remarks

This function treats the source buffer and the destination screen buffer as two-dimensional arrays (columns and rows of character cells). The region rectangle specifies the size and location of the block to be written to in the console screen buffer. A rectangle of the same size is located with its upper-left cell at the coordinates of the dwbuffer_coord parameter in the buffer. Data from the cells that are in the intersection of this rectangle and the source buffer rectangle is written to the destination rectangle.

Cells in the destination rectangle whose corresponding source location are outside the boundaries of the source buffer rectangle are left unaffected by the write operation. In other words, these are the cells for which no data is available to be written.

string ReadOutputCharacter( Handle h, integer length, Coord position )

Copies a specified number of characters from consecutive cells of a console screen buffer, beginning at a specified location.

Parameters

Return value

If the function succeeds, the return value is a string containing the characters read from the screen buffer. Otherwise, the return value is nil.

Remarks

If the number of characters to be read from extends beyond the end of the specified screen buffer row, characters are read from the next row. If the number of characters to be read from extends beyond the end of the console screen buffer, characters up to the end of the console screen buffer are read.

string ReadOutputAttribute( Handle h, integer length, Coord position )

Copies a specified number of character attributes from consecutive cells of a console screen buffer, beginning at a specified location.

Parameters

Return value

If the function succeeds, the return value is a string containing the attributes read from the screen buffer. Otherwise, the return value is nil.

Remarks

If the number of attributes to be read from extends beyond the end of the specified screen buffer row, attributes are read from the next row. If the number of attributes to be read from extends beyond the end of the console screen buffer, attributes up to the end of the console screen buffer are read.

string WriteOutputCharacter( Handle h, string characters, Coord position )

Copies a number of characters to consecutive cells of a console screen buffer, beginning at a specified location.

Parameters

Return value

If the function succeeds, the return value is the number of characters written. Otherwise, the return value is nil.

Remarks

If the number of characters to be written to extends beyond the end of the specified row in the console screen buffer, characters are written to the next row. If the number of characters to be written to extends beyond the end of the console screen buffer, characters are written up to the end of the console screen buffer.

The attribute values at the positions written to are not changed.

string WriteOutputAttribute( Handle h, string attributes, Coord position )

Copies a number of character attributes to consecutive cells of a console screen buffer, beginning at a specified location.

Parameters

Return value

If the function succeeds, the return value is the number of attributes written. Otherwise, the return value is nil.

Remarks

If the number of attributes to be written to extends beyond the end of the specified row in the console screen buffer, attributes are written to the next row. If the number of attributes to be written to extends beyond the end of the console screen buffer, the attributes are written up to the end of the console screen buffer.

The character values at the positions written to are not changed.

string FillOutputCharacter( Handle h, Char character, integer length, Coord position )

Writes a character to the console screen buffer a specified number of times, beginning at the specified coordinates.

Parameters

Return value

If the function succeeds, the return value is the number of characters written. Otherwise, the return value is nil.

Remarks

If the number of characters to write to extends beyond the end of the specified row in the console screen buffer, characters are written to the next row. If the number of characters to write to extends beyond the end of the console screen buffer, the characters are written up to the end of the console screen buffer.

The attribute values at the positions written are not changed.

string FillOutputAttribute( Handle h, Attrib attribute, integer length, Coord position )

Sets the character attributes for a specified number of character cells, beginning at the specified coordinates in a screen buffer.

Parameters

Return value

If the function succeeds, the return value is the number of characters written. Otherwise, the return value is nil.

Remarks

If the number of character cells whose attributes are to be set extends beyond the end of the specified row in the console screen buffer, the cells of the next row are set. If the number of cells to write to extends beyond the end of the console screen buffer, the cells are written up to the end of the console screen buffer.

The character values at the positions written to are not changed.

table GetScreenBufferInfo ( Handle h )

Retrieves information about the specified console screen buffer.

Parameters

Return Value

If the function succeeds, it returns a table containing the requested console screen buffer info.

Remarks

The rectangle returned in Window can be modified and then passed to the SetWindowInfo function to scroll the console screen buffer in the window, to change the size of the window, or both.

All coordinates returned in the table are in character-cell coordinates, where the origin { 0, 0 } is at the upper-left corner of the console screen buffer.

table GetScreenBufferInfoEx ( Handle h )

Retrieves extended information about the specified console screen buffer.

Parameters

Return Value

If the function succeeds, the return value is a table containing the requested console screen buffer info. Otherwise, the return value is nil.

Remarks

The rectangle returned in Window can be modified and then passed to the SetWindowInfo function to scroll the console screen buffer in the window, to change the size of the window, or both.

All coordinates returned in the table are in character-cell coordinates, where the origin { 0, 0 } is at the upper-left corner of the console screen buffer.

integer, integer GetScreenBufferSize ( Handle h )

Get the size of the console screen buffer.

Parameters

Return Value

If the function succeeds, the return value is the size of the console screen buffer, in character columns and rows.

integer, integer GetCursorPosition ( Handle h )

Get the position of the cursor in the console screen buffer.

Parameters

Return Value

If the function succeeds, the return value is the column and row coodinates of the cursor in the console screen buffer.

integer GetTextAttribute ( Handle h )

Get the currently set attributes for the console screen buffer.

Parameters

Return Value

If the function succeeds, the return value is the attributes of the characters written to a screen buffer by the Write function or echoed to a screen buffer by the Read function. Otherwise, the return value is nil.

integer, integer, integer, integer GetScreenBufferRect ( Handle h )

Get the current display window for the console screen buffer.

Parameters

Return Value

If the function succeeds, the return value is the console screen buffer coordinates of the left, top, right, and bottom of the display window. Otherwise, the return value is nil.

integer GetPopupAttributes ( Handle h )

Get the fill attribute for console pop-ups.

Parameters

Return Value

If the function succeeds, the return value is the fill attribute for console pop-ups. Otherwise, the return value is nil.

boolean GetFullscreenSupported ( Handle h )

Get whether full-screen mode is supported by the console.

Parameters

Return Value

If the function succeeds, the return value is a boolean indicating whether full-screen mode is supported by the console. Otherwise, the return value is nil.

table GetColor ( Handle h )

Get an array of color codes that describe the console's color settings.

Parameters

Return Value

If the function succeeds, the return value is an array of 16 RGB color triplets (e.g. { 255, 0, 0 } for pure red) that describe the console's color settings. Othwerise, the return value is nil.

integer, integer, integer GetColor ( Handle h, integer index )

Get a specific color value from the color table.

Parameters

Return Value

If the function succeeds, the return value is the red, green, and blue components of the color. Otherwise, the return value is nil.

boolean SetScreenBufferInfoEx ( Handle h, table info )

Sets extended information about the specified console screen buffer.

Parameters

Return Value

If the function succeeds, the return value is true. Otherwise, the return value is false.

Remarks

Fields specified in the info table will set the corresponding values in the screen buffer information. Any fields not specified will keep their previous values.

boolean SetColor ( Handle h, table colortable )

Set the console's colors.

Parameters

Return Value

If the function succeeds, the return value is true. Otherwise, the return value is false.

boolean SetColor ( Handle h, integer index, Color color )

Set a particular console color.

Parameters

Return Value

If the function succeeds, the return value is true. Otherwise, the return value is false.

integer, integer GetLargestWindowSize ( Handle h )

Retrieves the size of the largest possible console window, based on the current font and the size of the display.

Parameters

Return Value

The return value is maximum size of the console window, in character columns and rows, based on the current font and size of the display.

integer, boolean GetCursorInfo ( Handle h )

Retrieves information about the size and visibility of the cursor for the specified console screen buffer.

Parameters

Return Value

If the function succeeds, the return values are the cursor size and visibility. Otherwise, the return value is nil.

integer GetCursorSize ( Handle h )

Retrieves the size of the cursor for the specified console screen buffer.

Parameters

Return Value

If the function succeeds, the return value is the cursor size. Otherwise, the return value is nil.

boolean GetCursorVisible ( Handle h )

Retrieves the visibility of the cursor for the specified console screen buffer.

Parameters

Return Value

If the function succeeds, the return value is the cursor visibility. Otherwise, the return value is nil.

table GetCurrentFont ( Handle h, [ boolean maximum ] )

Retrieves information about the current console font.

Parameters

Return Value

If the function succeeds, the return value is a table containing font information

table GetHistoryInfo ()

Retrieves the history settings for the calling process's console.

Return Value

If the function succeeds, the return value is a table containing history settings. Otherwise, the return value is nil.

boolean SetHistoryInfo ( table info )

Sets the history settings for the calling process's console.

Parameters

Return Value

If the function succeeds, the return value is true. Otherwise, the return value is false.

Remarks

Fields specified in the info table will set the corresponding values in the history settings. Any fields not specified will keep their previous values.

table GetSelectionInfo ()

Retrieves information about the current console selection.

Return Value

If the function succeeds, the return value is a table containng selection information. Otherwise, the return value is nil.

boolean SetActiveScreenBuffer ( Handle h )

Sets the specified screen buffer to be the currently displayed console screen buffer.

Parameters

Return Value

If the function succeeds, the return value is true. Otherwise, the return value is false.

boolean SetScreenBufferSize ( Handle h, Coord size )

Changes the size of the specified console screen buffer.

Parameters

Return Value

If the function succeeds, the return value is true. Otherwise, the return value is false.

Remarks

The specified width and height cannot be less than the width and height of the console screen buffer's window. The specified dimensions also cannot be less than the minimum size allowed by the system. This minimum depends on the current font size for the console (selected by the user) and the minimum window size in pixels.

boolean SetCursorPosition ( Handle h, Coord position )

Sets the cursor position in the specified console screen buffer.

Parameters

Return Value

If the function succeeds, the return value is true. Otherwise, the return value is false.

Remarks

The cursor position determines where characters written by the Write function, or echoed by the Read function, are displayed. To determine the current position of the cursor, use the GetScreenBufferInfo or GetCursorPosition functions.

If the new cursor position is not within the boundaries of the console screen buffer's window, the window origin changes to make the cursor visible.

boolean SetCursorInfo ( Handle h, CursorInfo info )

Sets the size and visibility of the cursor for the specified console screen buffer.

Parameters

Return Value

If the function succeeds, the return value is true. Otherwise, the return value is false.

boolean SetCursorSize ( Handle h, boolean size )

Sets the size of the cursor for the specified console screen buffer.

Parameters

Return Value

If the function succeeds, the return value is true. Otherwise, the return value is false.

boolean SetCursorVisible ( Handle h, boolean visible )

Sets the visibility of the cursor for the specified console screen buffer.

Parameters

Return Value

If the function succeeds, the return value is true. Otherwise, the return value is false.

boolean ScrollScreenBuffer ( Handle h, Rect scroll_rect, [ Rect clip_rect ], Coord dest_origin, CharInfo fill )

Moves a block of data in a screen buffer. The effects of the move can be limited by specifying a clipping rectangle, so the contents of the console screen buffer outside the clipping rectangle are unchanged.

Parameters

Return Value

If the function succeeds, the return value is true. Otherwise, the return value is false.

Remarks

This function copies the contents of a rectangular region of a screen buffer, specified by the scroll_rect parameter, to another area of the console screen buffer. The target rectangle has the same dimensions as the scroll_rect rectangle with its upper-left corner at the coordinates specified by the dest_origin parameter. Those parts of scroll_rect that do not overlap with the target rectangle are filled in with the character and color attributes specified by the fill parameter.

The clipping rectangle applies to changes made in both the scroll_rect rectangle and the target rectangle. For example, if the clipping rectangle does not include a region that would have been filled by the contents of fill, the original contents of the region are left unchanged.

If the scroll or target regions extend beyond the dimensions of the console screen buffer, they are clipped. For example, if scroll_rect is the region contained by (0,0) and (19,19) and dest_origin is (10,15), the target rectangle is the region contained by (10,15) and (29,34). However, if the console screen buffer is 50 characters wide and 30 characters high, the target rectangle is clipped to (10,15) and (29,29). Changes to the console screen buffer are also clipped according to clip_rect, if specified. If the clipping rectangle is specified as (0,0) and (49,19), only the changes that occur in that region of the console screen buffer are made.

boolean SetWindowInfo ( Handle h, boolean absolute, Rect window )

Sets the current size and position of a console screen buffer's window.

Parameters

Return Value

If the function succeeds, the return value is true. Otherwise, the return value is false.

Remarks

The function fails if the specified window rectangle extends beyond the boundaries of the console screen buffer. This means that the Top and Left members of the window rectangle (or the calculated top and left coordinates, if absolute is FALSE) cannot be less than zero. Similarly, the Bottom and Right members (or the calculated bottom and right coordinates) cannot be greater than (screen buffer height – 1) and (screen buffer width – 1), respectively. The function also fails if the Right member (or calculated right coordinate) is less than or equal to the Left member (or calculated left coordinate) or if the Bottom member (or calculated bottom coordinate) is less than or equal to the Top member (or calculated top coordinate).

For consoles with more than one screen buffer, changing the window location for one screen buffer does not affect the window locations of the other screen buffers.

To determine the current size and position of a screen buffer's window, use the GetScreenBufferInfo function. This function also returns the maximum size of the window, given the current screen buffer size, the current font size, and the screen size. The GetLargestWindowSize function returns the maximum window size given the current font and screen sizes, but it does not consider the size of the console screen buffer.

This function can be used to scroll the contents of the console screen buffer by shifting the position of the window rectangle without changing its size.

boolean SetTextAttribute ( Handle h, Attribute attributes )

Sets the attributes of characters written to the console screen buffer by the Write function, or echoed by the Read function. This function affects text written after the function call.

Parameters

Return Value

If the function succeeds, the return value is true. Otherwise, the return value is false.

Remarks

To determine the current color attributes of a screen buffer, call the GetScreenBufferInfo or GetTextAttribute functions.

string GetTitle ()

Retrieves the title for the current console window.

Return Value

If the function succeeds, the return value is a string containing the title. Otherwise, the return value is nil.

string GetOriginalTitle ()

Retrieves the original title for the current console window.

Return Value

If the function succeeds, the return value is a string containing the original title. Otherwise, the return value is nil.

Remarks

To set the title for a console window, use the SetTitle function. To retrieve the current title string, use the GetTitle function.

boolean SetTitle ( string title )

Sets the title for the current console window.

Parameters

Remarks

When the process terminates, the system restores the original console title.

Handle CreateScreenBuffer ()

Creates a console screen buffer.

Return Value

If the function succeeds, the return value is a handle to the new console screen buffer. Otherwise, the return value is nil.

Remarks

A console can have multiple screen buffers but only one active screen buffer. Inactive screen buffers can be accessed for reading and writing, but only the active screen buffer is displayed. To make the new screen buffer the active screen buffer, use the SetActiveScreenBuffer function.

The calling process can use the returned handle in any function that requires a handle to a console screen buffer.

To close the console screen buffer handle, use the CloseHandle function.

integer GetMode ( Handle h )

Retrieves the current input mode of a console's input buffer or the current output mode of a console screen buffer.

Parameters

Return Value

If the function succeeds, the return value is an integer combining several flag values. Otherwise, the return value is nil.

Input:

Screen Buffer:

Remarks

A console consists of an input buffer and one or more screen buffers. The mode of a console buffer determines how the console behaves during input or output (I/O) operations. One set of flag constants is used with input handles, and another set is used with screen buffer (output) handles. Setting the output modes of one screen buffer does not affect the output modes of other screen buffers.

The ENABLE_LINE_INPUT and ENABLE_ECHO_INPUT modes only affect processes that use Read to read from the console's input buffer. Similarly, the ENABLE_PROCESSED_INPUT mode primarily affects Read users, except that it also determines whether CTRL+C input is reported in the input buffer (to be read by the ReadInput function) or is passed to a function defined by the application.

The ENABLE_WINDOW_INPUT and ENABLE_MOUSE_INPUT modes determine whether user interactions involving window resizing and mouse actions are reported in the input buffer or discarded. These events can be read by ReadInput, but they are always filtered by Read.

The ENABLE_PROCESSED_OUTPUT and ENABLE_WRAP_AT_EOL_OUTPUT modes only affect processes using Read and Write.

To change a console's I/O modes, call SetMode.

Read

Reads character input from the console input buffer and removes it from the buffer.

Parameters

Return Value

If the function succeeds, the return value is a string containing data read from the console input buffer. Otherwise, the return value is nil.

Remarks

This function reads keyboard input from a console's input buffer, up to 64K.

To retrieve and set the input modes of a console input buffer, use the GetMode and SetMode functions.

If the input buffer contains input events other than keyboard events (such as mouse events or window-resizing events), they are discarded. Those events can only be read by using the ReadInput function.

boolean SetMode ( Handle h, integer mode )

Sets the input mode of a console's input buffer or the output mode of a console screen buffer.

Parameters

Return Value

If the function succeeds, the return value is true. Otherwise, the return value is false.

boolean Write (Handle h, string characters )

Writes a character string to a console screen buffer beginning at the current cursor location.

Parameters

Return Value

If the function succeeds, the return value is true. Otherwise, the return value is false.

Remarks

This function writes characters to the console screen buffer at the current cursor position. The cursor position advances as characters are written. The SetCursorPosition function sets the current cursor position.

Characters are written using the foreground and background color attributes associated with the console screen buffer. The SetTextAttribute function changes these colors. To determine the current color attributes and the current cursor position, use GetScreenBufferInfo or GetTextAttribute.

To retrieve and set the output modes of a console screen buffer, use the GetMode and SetMode functions.

Although an application can use WriteConsole in ANSI mode to write ANSI characters, consoles do not support ANSI escape sequences. However, some functions provide equivalent functionality. For more information, see SetCursorPos, SetTextAttribute, and SetCursorInfo.