Lua logo

Preface

This is the reference manual of MoonSDL2, which is a Lua binding library for the Simple DirectMedia Layer 2.0 (SDL2) and its extension libraries SDL_image, SDL_mixer, and SDL_ttf. [1]

It is assumed that the reader is familiar with both SDL2 and the Lua programming language.

For convenience of reference, this document contains external (deep) links to the Lua Reference Manual and the SDL2 wiki.

Getting and installing

For installation intructions, refer to the README file in the MoonSDL2 official repository on GitHub.

Module organization

The MoonSDL2 module is loaded using Lua’s require() and returns a table containing the functions it provides (as usual with Lua modules). This manual assumes that such table is named sdl, i.e. that it is loaded with:

 sdl = require("moonsdl2")

but nothing forbids the use of a different name.

Examples

Complete examples can be found in the examples/ directory of the release package.

License

MoonSDL2 is released under the MIT/X11 license (same as Lua, and with the same only requirement to give proper credits to the original author). The copyright notice is in the LICENSE file in the base directory of the official repository on GitHub.

See also

MoonSDL2 is part of MoonLibs, a collection of Lua libraries for graphics and audio programming.

Introduction

MoonSDL2 is an almost one-to-one Lua binding library to SDL2 and its extension libraries. This means that by and large, it is intended to be used as described in the SDL2 documentation (apart from coding in Lua, of course).

Not all SDL2’s APIs are exposed by MoonSDL2. In particular, the following APIs are not (or not yet) exposed: multithreading, file abstraction, shared object support, endianness handling, bit manipulation, platform-specific functionality, and standard library functionality. Moreover, audio functionalities are exposed only in terms of SDL_mixer API bindings (audio device management and audio streams APIs are not exposed).

This section gives a brief overview of the binding library, while the details are given in the sections that follow.

MoonSDL2 binds SDL2 objects (window, renderer, etc.) to Lua userdata, which are returned by the creating functions (sdl.create_window( ), sdl.create_renderer( ), etc) and are then used to refer to objects in Lua in the same way as one would use SDL2 handles in C.

As a general (but loose) rule, SDL2 functions are bound to MoonSDL2 functions or methods whose names are snake_case versions of the original one.

The functions related to an object type - with the exception of the creating function - are usually bounded to methods of that object (e.g. the C function SDL_SetWindowTitle(window, …​) becomes the method window:set_title(…​) in Lua.

Objects are garbage collected at exit (which includes on error), and automatically deleted at the SDL2 level, so there is no need to explicitly invoke their release methods (free( ), or whatever else) at exit for cleanup.

Apart from at exit, however, objects are not automatically garbage collected [2] and one must release them explicitly when needed, e.g. to release resources when the application is not exiting and some objects are no longer needed.

Releasing an object causes the automatic (pre) destruction of all its children objects, and the invalidation of any reference to the object and to its children. [3]

SDL2 0-based indices are usually translated to 1-based indices in MoonSDL2.

If not stated otherwise, on error all MoonSDL2 functions raise a Lua error. If needed, this behaviour can be overridden by wrapping function calls in the standard Lua pcall( ).

Initialization

  • sdlinitflags, imginitflags, mixinitflags = init( )
    sdlinitflags, imginitflags, mixinitflags = was_init( )
    Attempts to initialize all SDL2 subystems as well as the extension libraries.
    The returned flags can be used to check what was actually initialized.
    Rfr: SDL_Init, IMG_Init, Mix_Init, TTF_Init.

  • quit( )
    Cleans up all initialized subsystems and extension libraries.
    This function is automatically executed at exit (including on error).
    Rfr: SDL_Quit, IMG_Quit, Mix_Quit, TTF_Quit.

hints

  • boolean = reset_hint(name)
    reset_hints( )
    Rfr: SDL_ResetHint, SDL_ResetHints.

  • hintcb = add_hint_callback(name, func)
    hintcb:del( )
    The passed callback func is executed as func(name, oldval, newval), where all arguments are strings (or nil for unset values).
    To unregister the callback, use the del( ) method of the returned hintcb object.
    Rfr: SDL_AddHintCallback.

Video display

  • ddpi, hdpi, vdpi = get_display_dpi(displayindex)
    ddpi, hdpi, vdpi = integers.
    Rfr: SDL_GetDisplayDPI.

window

  • window:flash(op)
    mode: 'cancel', 'briefly', or 'until focused'.
    Rfr: SDL_FlashWindow.

  • window:set_hit_test([func])
    The func callback is executed as result = func(window, area) where area is a point and the returned result must be a hittestresult value.
    Passing func=nil disables hit-testing.
    Rfr: SDL_SetWindowHitTest.

glcontext

Rendering (2D)

surface

  • surface:save_bmp(file)
    surface:save_png(file)
    surface:save_jpg(file, quality)
    file: string (pathname),
    quality: integer.
    Rfr: SDL_SaveBMP, IMG_SavePNG, IMG_SaveJPG.

renderer

texture

animation

  • w, h = animation:get_size( )
    numframes = animation:get_count( )
    frames = animation:get_frames( )
    delays = animation:get_delays( )
    w, h, numframes: integer.
    frames: {surface}[numframes],
    delays: {integer}[numframes], (milliseconds).
    Rfr: IMG_Animation.

pixel format

Note that pxlfmt (an object) corresponds to SDL_PixelFormat, whereas pixelformat (an enum) corresponds to SDL_PixelFormatEnum.

  • pixelformat = pxlfmt:get_format( )
    pixel = pxlfmt:map_rgb(r, g, b)
    pixel = pxlfmt:map_rgba(r, g, b, a)
    r, g, b = pxlfmt:get_rgb(pixel)
    r, g, b, a = pxlfmt:get_rgba(pixel)
    pixel = integer,
    r, g, b, a: integer (0 .. 255).
    Rfr: SDL_MapRGB, SDL_MapRGBA, SDL_GetRGB, SDL_GetRGBA.

palette

  • palette = alloc_palette(ncolors)
    palette:free( )
    ncolors: integer.
    Rfr: SDL_AllocPalette.

font

Rfr: SDL2_ttf.

Event handling

  • push_user_event(code, [data])
    code: integer (int32_t),
    data: any Lua value (or nil).
    When its time come, the event will be dispatched to the user as a userevent.
    Rfr: SDL_PushEvent.

Input devices

keyboard

Referring to the table at SDL_Scancode, in the following functions name is the Key Name (a string), scancode is the SDL_Scancode Value (an integer), and keycode is the SDL_Keycode Value (also an integer). The sdl table contains sdl.SCANCODE_XXX entries for SDL_SCANCODE_XXX values, and sdl.KEYCODE_XXX entries for SDLK_XXX values.

mouse

cursor

joystick

gamecontroller

haptic

touch

sensor

Audio mixer

Rfr: SDL2_mixer.

Note
SDL_mixer uses the term 'channel' to refer both to audio channels (mono/stereo/surround), and to separate sources of audio data. To avoid confusion, the latter are here renamed as tracks.
  • open_audio(frequency, [audioformat], channels, chunksize)
    close_audio( )
    The following definitions are available: sdl.MIX_DEFAULT_FREQUENCY, sdl.MIX_DEFAULT_FORMAT, and sdl.MIX_DEFAULT_CHANNELS.
    Rfr: Mix_OpenAudio, Mix_CloseAudio.

  • set_master_volume(value)
    value = get_master_volume( )
    value: integer (0 .. sdl.MIX_MAX_VOLUME).
    Rfr: Mix_MasterVolume.

tracks

  • track_set_panning([track], left, right)
    track_unset_panning([track])
    track: integer, or nil for all tracks.
    left, right: integer (0 .. 255).
    Rfr: Mix_SetPanning.

  • track_set_volume([track], value)
    value = track_get_volume([track])
    value: integer (0 .. sdl.MIX_MAX_VOLUME).
    Rfr: Mix_Volume.

  • track_halt([track])
    track_pause([track])
    track_resume([track])
    boolean, n = track_paused([track])
    boolean, n = track_playing([track])
    n: integer (no. of tracks in the queried state, returned only if track=nil).
    Rfr: Mix_HaltChannel, Mix_Pause, Mix_Resume, Mix_Paused, Mix_Playing.

  • n = track_expire([track], [ms])
    ms: integer (milliseconds), or nil to remove the expiration.
    n: integer (no. of channels that changed expirations).
    Rfr: Mix_ExpireChannel.

  • set_track_finished_callback([func])
    The func callback is executed as func(track).
    Passing func=nil unregisters the callback.
    Rfr: Mix_ChannelFinished.

  • group_add(tag, track)
    group_add(tag, fromtrack, totrack)
    group_remove(track)
    group_remove(fromtrack, totrack)
    ntracks = group_count(tag)
    tag: integer (tag = -1 is reserved for removal operations).
    Rfr: Mix_GroupChannels Mix_GroupCount.

chunks

  • chunk:set_volume(value)
    value = chunk:get_volume( )
    value: integer (0 .. sdl.MIX_MAX_VOLUME).
    Rfr: Mix_VolumeChunk.

music

  • music:set_volume(value)
    value = music:get_volume( )
    music_set_volume(value)
    value = music_get_volume( )
    value: integer (0 .. sdl.MIX_MAX_VOLUME).
    Rfr: Mix_SetVolumeMusic, Mix_GetVolumeMusic.

  • set_music_finished_callback([func])
    The func callback is executed as func( ).
    Passing func=nil unregisters the callback.
    Rfr: Mix_HookMusicFinished.

Time handling

ticks

The following alternative time utilities are also available (they are consistent with the time utilities that can be found in other libraries of the MoonLibs collection).

  • t = now( )
    Returns the current time in seconds (float).
    The returned time is relative to an unspecified point in the past, and unrelated to the time in milliseconds returned by get_ticks( ).
    This is implemented with monotonic clock_gettime(3), if available, or with gettimeofday(3) otherwise.

  • dt = since(t)
    Returns the time in seconds (float) elapsed since the time t, previously obtained with now( ).

  • sleep(seconds)
    Sleeps for seconds (float).

timer

  • timer = start_timer(timeout, func)
    timer:stop( )
    timeout: integer (milliseconds).
    The func callback is executed at the expiration of the timer as restart = func(timer).
    If the callback returns false (or nil), the timer is deleted, othewise it is restarted with the same timeout value.
    The stop( ) method stops and deletes the timer.
    Rfr: SDL_AddTimer.

Miscellanea

messagebox

  • messagebox = create_message_box(messageboxdata)
    messagebox:set_color_scheme([colors])
    buttonid = messagebox:show( )
    messagebox:delete( )
    buttonid: integer (identifying the pressed button),
    colors: {color}[5], defining (in this order) the color of 1) background, 2) text, 3) button border, 4) button background, and 5) button selected. Only the rgb components are relevant (any alpha component is ignored). Pass colors=nil to restore the default color scheme.
    Rfr: SDL_ShowMessageBox.

rectangle functions

log functions

Rfr: Log Handling.

  • log_set_output_function([func])
    The passed callback func is executed as func(category, priority, message).
    Passing func=nil unregisters the callback.
    SDL_LogSetOutputFunction.

other functions

  • trace_objects(boolean)
    Enable/disable tracing of objects creation and destruction (which by default is disabled).
    If enabled, a printf is generated whenever an object is created or deleted, indicating the object type and the value of its raw SDL2 handle.

Structs and data types

In this document, the float and integer types denote Lua numbers, while other types such as boolean, string, etc denote standard Lua types. Note that float here just means 'floating point' as opposed to 'integer', and does not imply single-precision.

Events returned by event handling functions and a few other structs used in the SDL2 C API are represented as string-indexed Lua tables, and are described in the subsections that follow.

point, rect, color

Points, rects, and colors are by default represented as Lua arrays containing float elements. The meaning of the elements thus depends on their position, as detailed below, and there is no syntactic sugar such as v.x and v.y to access them.

  • point = {x, y}
    All elements are integers.
    (Rfr: SDL_Point)

  • fpoint = {x, y}
    All elements are floats.
    (Rfr: SDL_FPoint)

  • rect = {x, y, w, h}
    All elements are integers.
    (Rfr: SDL_Rect)

  • frect = {x, y, w, h}
    All elements are floats.
    (Rfr: SDL_FRect)

  • color = {r, g, b, a}
    All elements are integers (0..255).
    (Rfr: SDL_Color)

  • vertex = { position, color, texcoord }
    position: fpoint,
    color: color,
    texcoord: fpoint (opt.).
    (Rfr: SDL_Vertex)

memptr

A memptr object is a Lua light userdata representing a C pointer (void*) to a contiguous memory area of suitable size, where 'suitable' depends on the context. The size is not checked by MoonSDL2, thus beware of the potential dangers.

How such an object is accessed (or obtained, when passed as an argument) is not specified here. One may, for example, use hostmem objects from the MoonGLMATH library.

events

Rfr: SDL_Event.

An event is one of the structs described in this section, depending on the type field value (eventtype) as per the following list:

type: struct
'firstevent': commonevent,
'quit': commonevent,
'app terminating': commonevent,
'app lowmemory': commonevent,
'app willenterbackground': commonevent,
'app didenterbackground': commonevent,
'app willenterforeground': commonevent,
'app didenterforeground': commonevent,
'localechanged': commonevent,
'displayevent': displayevent,
'windowevent': windowevent,
'syswmevent': commonevent,
'keydown': keyboardevent,
'keyup': keyboardevent,
'textediting': texteditingevent,
'textinput': textinputevent,
'keymapchanged': commonevent,
'mousemotion': mousemotionevent,
'mousebuttondown': mousebuttonevent,
'mousebuttonup': mousebuttonevent,
'mousewheel': mousewheelevent,
'joyaxismotion': joyaxisevent,
'joyballmotion': joyballevent,
'joyhatmotion': joyhatevent,
'joybuttondown': joybuttonevent,
'joybuttonup': joybuttonevent,
'joydeviceadded': joydeviceaddedevent,
'joydeviceremoved': joydeviceremovedevent,
'joybatteryupdated': joybatteryevent,
'controlleraxismotion': controlleraxisevent,
'controllerbuttondown': controllerbuttonevent,
'controllerbuttonup': controllerbuttonevent,
'controllerdeviceadded': controllerdeviceaddedevent,
'controllerdeviceremoved': controllerdeviceevent,
'controllerdeviceremapped': controllerdeviceevent,
'controllertouchpaddown': controllertouchpadevent,
'controllertouchpadmotion': controllertouchpadevent,
'controllertouchpadup': controllertouchpadevent,
'controllersensorupdate': controllersensorevent,
'fingerdown': fingerevent,
'fingerup': fingerevent,
'fingermotion': fingerevent,
'dollargesture': dollargestureevent,
'dollarrecord': dollargestureevent,
'multigesture': multigestureevent,
'clipboardupdate': commonevent,
'dropfile': dropevent,
'droptext': dropevent,
'dropbegin': dropevent,
'dropcomplete': dropevent,
'audiodeviceadded': commonevent,
'audiodeviceremoved': commonevent,
'sensorupdate': sensorevent,
'render targets reset': commonevent,
'render device reset': commonevent,
'pollsentinel': commonevent,
'userevent': userevent,
'lastevent': commonevent.

  • commonevent = {
    type: eventtype,
    timestamp: integer (milliseconds),
    } (rfr: SDL_Event)

  • displayevent = {
    type: 'displayevent',
    timestamp: integer (milliseconds),
    display: integer (1-based index),
    event: displayeventtype,
    data: integer,
    } (rfr: SDL_DisplayEvent)

  • windowevent = {
    type: 'windowevent',
    timestamp: integer (milliseconds),
    window: window,
    event: windoweventtype,
    data1: integer,
    data2: integer,
    } (rfr: SDL_WindowEvent)

  • keyboardevent = {
    type: 'keydown' or 'keyup',
    timestamp: integer (milliseconds),
    window: window,
    state: keystate,
    repeat: boolean,
    keycode: integer,
    scancode: integer,
    name: string (see SDL_Keycode)),
    mod: keymod,
    } (rfr: SDL_KeyboardEvent)

  • texteditingevent = {
    type: 'textediting',
    timestamp: integer (milliseconds),
    window: window,
    text: string,
    start: integer,
    length: integer,
    } (rfr: SDL_TextEditingEvent)

  • textinputevent = {
    type: 'textinput',
    timestamp: integer (milliseconds),
    window: window,
    text: string,
    } (rfr: SDL_TextInputEvent)

  • mousemotionevent = {
    type: 'mousemotion',
    timestamp: integer (milliseconds),
    window: window,
    id: integer,
    x: integer,
    y: integer,
    xrel: integer,
    yrel: integer,
    state: mousebuttonstate,
    } (rfr: SDL_MouseMotionEvent)

  • mousebuttonevent = {
    type: 'mousebuttondown' or 'mousebuttonup',
    timestamp: integer (milliseconds),
    window: window,
    id: integer,
    x: integer,
    y: integer,
    button: button,
    state: keystate,
    clicks: integer,
    } (rfr: SDL_MouseButtonEvent)

  • mousewheelevent = {
    type: 'mousewheel',
    timestamp: integer (milliseconds),
    window: window,
    id: integer,
    x: integer,
    y: integer,
    precise_x: float,
    precise_y: float,
    direction: mousewheeldir,
    } (rfr: SDL_MouseWheelEvent)

  • joyaxisevent = {
    type: 'joyaxismotion',
    timestamp: integer (milliseconds),
    joystick: joystick,
    id: integer,
    axis: integer,
    value: integer,
    } (rfr: SDL_JoyAxisEvent)

  • joyballevent = {
    type: 'joyballmotion',
    timestamp: integer (milliseconds),
    joystick: joystick,
    id: integer,
    ball: integer,
    xrel: integer,
    yrel: integer,
    } (rfr: SDL_JoyBallEvent)

  • joyhatevent = {
    type: 'joyhatmotion',
    timestamp: integer (milliseconds),
    joystick: joystick,
    id: integer,
    hat: integer,
    value: hatstate,
    } (rfr: SDL_JoyHatEvent)

  • joybuttonevent = {
    type: 'joybuttondown' or 'joybuttonup',
    timestamp: integer (milliseconds),
    joystick: joystick,
    id: integer,
    button: integer,
    state: keystate,
    } (rfr: SDL_JoyButtonEvent)

  • joydeviceaddedevent = {
    type: 'joydeviceadded',
    timestamp: integer (milliseconds),
    device_index: integer,
    } (rfr: SDL_JoyDeviceEvent)

  • joydeviceremovedevent = {
    type: 'joydeviceremoved',
    timestamp: integer (milliseconds),
    joystick: joystick,
    id: integer,
    } (rfr: SDL_JoyDeviceEvent)

  • joybatteryevent = {
    type: 'joybatteryupdated',
    timestamp: integer (milliseconds),
    joystick: joystick,
    id: integer,
    level: joystickpowerlevel,
    } (rfr: SDL_JoyBatteryEvent)

  • controlleraxisevent = {
    type: 'controlleraxismotion',
    timestamp: integer (milliseconds),
    controller: gamecontroller,
    id: integer,
    axis: controlleraxis,
    value: integer,
    } (rfr: SDL_ControllerAxisEvent)

  • controllerbuttonevent = {
    type: 'controllerbuttondown' or 'controllerbuttonup',
    timestamp: integer (milliseconds),
    controller: gamecontroller,
    id: integer,
    button: controllerbutton,
    state: keystate,
    } (rfr: SDL_ControllerButtonEvent)

  • controllerdeviceaddedevent = {
    type: 'controllerdeviceadded',
    timestamp: integer (milliseconds),
    device_index: integer,
    } (rfr: SDL_ControllerDeviceEvent)

  • controllerdeviceevent = {
    type: 'controllerdeviceremoved' or 'controllerdeviceremapped',
    timestamp: integer (milliseconds),
    controller: gamecontroller,
    id: integer,
    } (rfr: SDL_ControllerDeviceEvent)

  • controllertouchpadevent = {
    type: 'controllertouchpaddown', 'controllertouchpadup', or 'controllertouchpadmotion',
    timestamp: integer (milliseconds),
    controller: gamecontroller,
    id: integer,
    touch_id: integer,
    finger_id: integer,
    x: float,
    y: float,
    pressure: float,
    } (rfr: SDL_ControllerTouchpadEvent)

  • controllersensorevent = {
    type: 'controllersensorupdate',
    timestamp: integer (milliseconds),
    controller: gamecontroller,
    id: integer,
    sensor: sensortype data: {float}[3],
    } (rfr: SDL_ControllerSensorEvent)

  • fingerevent = {
    type: 'fingerdown', 'fingerup', or 'fingermotion',
    window: window,
    timestamp: integer (milliseconds),
    touch_id: integer,
    finger_id: integer,
    x: float,
    y: float,
    dx: float,
    dy: float,
    pressure: float,
    } (rfr: SDL_TouchFingerEvent)

  • dollargestureevent = {
    type: 'dollargesture' or 'dollarrecord',
    timestamp: integer (milliseconds),
    touch_id: integer,
    gesture_id: integer,
    num_fingers: integer,
    error: float,
    x: float,
    y: float,
    } (rfr: SDL_DollarGestureEvent)

  • multigestureevent = {
    type: 'multigesture',
    timestamp: integer (milliseconds),
    touch_id: integer,
    dtheta: float,
    ddist: float,
    x: float,
    y: float,
    num_fingers: integer,
    } (rfr: SDL_MultiGestureEvent)

  • dropevent = {
    type: 'dropfile', 'droptext', 'dropbegin', or 'dropcomplete',
    timestamp: integer (milliseconds),
    file: string (pathname),
    } (rfr: SDL_DropEvent)

  • sensorevent = {
    type: 'sensorupdate',
    timestamp: integer (milliseconds),
    sensor: sensor,
    id: integer,
    data: {float}[6],
    } (rfr: SDL_SensorEvent)

  • userevent = {
    type: 'userevent',
    timestamp: integer (milliseconds),
    code: integer,
    data: user defined Lua value,
    } (rfr: SDL_UserEvent)

haptic effects

An hapticeffect is one of the structs described in this section, depending on the type field value (haptictype) as per the following list:

type: struct
'constant': hapticconstant,
'sine': hapticperiodic,
'triangle': hapticperiodic,
'sawtoothup': hapticperiodic,
'sawtoothdown': hapticperiodic,
'leftright': hapticleftright,
'ramp': hapticramp,
'spring': hapticcondition,
'damper': hapticcondition,
'inertia': hapticcondition,
'friction': hapticcondition,
'custom': hapticcustom.

  • hapticconstant = {
    type: 'constant',
    dirtype: hapticdirection,
    dir: {integer}[3],
    length: integer,
    delay: integer,
    button: integer,
    interval: integer,
    level: integer,
    attack_length: integer,
    attack_level: integer,
    fade_length: integer,
    fade_level: integer,
    } (rfr: SDL_HapticConstant)

  • hapticperiodic = {
    type: 'sine' or 'triangle' or 'sawtoothup' or 'sawtoothdown' ,
    dirtype: hapticdirection,
    dir: {integer}[3],
    length: integer,
    delay: integer,
    button: integer,
    interval: integer,
    period: integer,
    magnitude: integer,
    offset: integer,
    phase: integer,
    attack_length: integer,
    attack_level: integer,
    fade_length: integer,
    fade_level: integer,
    } (rfr: SDL_HapticPeriodic)

  • hapticcondition = {
    type: 'spring' or 'damper' or 'inertia' or 'friction',
    dirtype: hapticdirection,
    dir: {integer}[3],
    length: integer,
    delay: integer,
    button: integer,
    inteval: integer,
    right_sat: {integer}[3],
    left_sat: {integer}[3],
    right_coeff: {integer}[3],
    left_coeff: {integer}[3],
    deadband: {integer}[3],
    center: {integer}[3],
    } (rfr: SDL_HapticCondition)

  • hapticramp = {
    type: 'ramp',
    dirtype: hapticdirection,
    dir: {integer}[3],
    length: integer,
    delay: integer,
    button: integer,
    interval: integer,
    start: integer,
    end: integer,
    attack_length: integer,
    attack_level: integer,
    fade_length: integer,
    fade_level: integer,
    } (rfr: SDL_HapticRamp)

  • hapticleftright = {
    type: 'leftright',
    length: integer,
    large_magnitude: integer,
    small_magnitude: integer,
    } (rfr: SDL_HapticLeftRight)

  • hapticcustom = {
    type: 'custom',
    dirtype: hapticdirection,
    dir: {integer}[3],
    length: integer,
    delay: integer,
    button: integer,
    interval: integer,
    channels: integer,
    period: integer,
    samples: integer,
    attack_length: integer,
    attack_level: integer,
    fade_length: integer,
    fade_level: integer,
    data: {integer}[samples*channels],
    } (rfr: SDL_HapticCustom)

other structs

  • controllerbuttonbind =
    { type: 'none' } or
    { type: 'button', button: integer } or
    { type: 'axis', axis: integer } or
    { type: 'hat', hat: integer, mask: hatstate }
    (rfr: SDL_GameControllerButtonBind)

  • displaymode = {
    format: pixelformat,
    w: integer,
    h: integer,
    refresh_rate: integer,
    driverdata: memptr,
    } (rfr: SDL_DisplayMode)

  • finger = {
    finger_id: integer,
    x: float,
    y: float,
    pressure: float,
    } (rfr: SDL_Finger)

  • hapticfeatures = {
    constant: boolean,
    sine: boolean,
    leftright: boolean,
    triangle: boolean,
    sawtoothup: boolean,
    sawtoothdown: boolean,
    ramp: boolean,
    spring: boolean,
    damper: boolean,
    inertia: boolean,
    friction: boolean,
    custom: boolean,
    gain: boolean,
    autocenter: boolean,
    status: boolean,
    pause: boolean,
    } (rfr: SDL_HapticQuery)

  • joystickguid = {integer}[16]

  • joystickguidinfo = {
    vendor: integer,
    product: integer,
    version: integer,
    crc16: integer,
    } (rfr: SDL_GetJoystickGUIDInfo)

  • keymod = {
    lshift: boolean,
    rshift: boolean,
    shift: boolean,
    lctrl: boolean,
    rctrl: boolean,
    ctrl: boolean,
    lalt: boolean,
    ralt: boolean,
    alt: boolean,
    lgui: boolean,
    rgui: boolean,
    gui: boolean,
    num: boolean,
    caps: boolean,
    mode: boolean,
    scroll: boolean,
    none: boolean,
    } (rfr: SDL_Keymod)

  • locale = {
    language: string,
    country: string or nil,
    } (rfr: SDL_GetPreferredLocales)

  • messageboxbuttondata = {
    flags: messageboxbuttonflags,
    buttonid: integer,
    text: string,
    } (rfr: SDL_MessageBoxButtonData)

  • messageboxdata = {
    flags: messageboxflags,
    window: window (opt.),
    title: string,
    message: string,
    buttons: {messageboxbuttondata},
    } (rfr: SDL_MessageBoxData)

  • mousebuttonstate = {
    left: boolean,
    right: boolean,
    middle: boolean,
    x1: boolean,
    x2: boolean,
    } (rfr: SDL_GetMouseState)

  • rendererinfo = {
    name: string,
    flags: rendererflags,
    texture_formats: pixelformat,
    max_texture_width: integer,
    max_texture_height: integer,
    } (rfr: SDL_RendererInfo)

  • touchdevice = {
    touch_id: integer,
    name: string type: touchdevicetype,
    num_fingers: integer,
    } (rfr: SDL_GetTouchDevice)

Enums

SDL2 enums are mapped in MoonSDL2 to sets of string literals (as is customary in Lua). For example, the C enum SDL_LogPriority is mapped to the Lua enum type logpriority,

and the C value SDL_LOG_PRIORITY_XXX is mapped to the string literal 'xxx' (lowercase version of the XXX part of the C value name, with underscores replaced by spaces).

If needed, the following function can be used to obtain the list of literals admitted by a particular enum type:

  • {literal} = sdl.enum(enumtype)
    Returns a table listing the literals admitted by enumtype (given as a string, e.g. 'hintpriority', 'logpriority', 'pixelformat' etc).

Below is the list of the enum types in MoonSDL2, together with their admitted literal values.

audioformat: AUDIO_XXX
Values: 'u8', 's8', 'u16', 's16', 'u16msb', 's16msb', 's32', 's32msb', 'f32', 'f32msb'.

blendfactor: SDL_BLENDFACTOR_XXX (SDL_BlendFactor)
Values: 'zero', 'one', 'src color', 'one minus src color', 'src alpha', 'one minus src alpha', 'dst color', 'one minus dst color', 'dst alpha', 'one minus dst alpha'.

blendoperation: SDL_BLENDOPERATION_XXX (SDL_BlendOperation)
Values: 'add', 'subtract', 'rev subtract', 'minimum', 'maximum'.

button: SDL_BUTTON_XXX
Values: 'left', 'right', 'middle', 'x1', 'x2'.

controlleraxis: SDL_CONTROLLER_AXIS_XXX (SDL_GameControlleAxis)
Values: 'invalid', 'leftx', 'lefty', 'rightx', 'righty', 'triggerleft', 'triggerright'.

controllerbindtype: SDL_CONTROLLER_BINDTYPE_XXX (SDL_GameControllerBindType)
Values: 'none', 'button', 'axis', 'hat'.

controllerbutton: SDL_CONTROLLER_BUTTON_XXX (SDL_GameControllerButton)
Values: 'invalid', 'a', 'b', 'x', 'y', 'back', 'guide', 'start', 'leftstick', 'rightstick', 'leftshoulder', 'rightshoulder', 'dpad up', 'dpad down', 'dpad left', 'dpad right', 'misc1', 'paddle1', 'paddle2', 'paddle3', 'paddle4', 'touchpad'.

controllertype: SDL_CONTROLLER_TYPE_XXX (SDL_GameControllerType)
Values: 'unknown', 'xbox360', 'xboxone', 'ps3', 'ps4', 'nintendo switch pro', 'virtual', 'ps5', 'amazon luna', 'google stadia', 'nvidia shield', 'nintendo switch joycon left', 'nintendo switch joycon right', 'nintendo switch joycon pair'.

displayeventtype: SDL_DISPLAYEVENT_XXX (SDL_DisplayEventID)
Values: 'none', 'orientation', 'connected', 'disconnected'.

eventtype: SDL_XXX (SDL_EventType)
Values: 'firstevent', 'quit', 'app terminating', 'app lowmemory', 'app willenterbackground', 'app didenterbackground', 'app willenterforeground', 'app didenterforeground', 'localechanged', 'displayevent', 'windowevent', 'syswmevent', 'keydown', 'keyup', 'textediting', 'textinput', 'keymapchanged', 'mousemotion', 'mousebuttondown', 'mousebuttonup', 'mousewheel', 'joyaxismotion', 'joyballmotion', 'joyhatmotion', 'joybuttondown', 'joybuttonup', 'joydeviceadded', 'joydeviceremoved', 'joybatteryupdated', 'controlleraxismotion', 'controllerbuttondown', 'controllerbuttonup', 'controllerdeviceadded', 'controllerdeviceremoved', 'controllerdeviceremapped', 'controllertouchpaddown', 'controllertouchpadmotion', 'controllertouchpadup', 'controllersensorupdate', 'fingerdown', 'fingerup', 'fingermotion', 'dollargesture', 'dollarrecord', 'multigesture', 'clipboardupdate', 'dropfile', 'droptext', 'dropbegin', 'dropcomplete', 'audiodeviceadded', 'audiodeviceremoved', 'sensorupdate', 'render targets reset', 'render device reset', 'pollsentinel', 'userevent', 'lastevent'.

fading: MIX_XXX (Mix_Fading)
Values: 'no fading', 'fading out', 'fading in'.

flashoperation: SDL_FLASH_XXX (SDL_FlashOperation)
Values: 'cancel', 'briefly', 'until focused'.

fontalign: TTF_WRAPPED_ALIGN_XXX
Values: 'left', 'center', 'right'.

fontdirection: TTF_DIRECTION_XXX (TTF_Direction)
Values: 'ltr', 'rtl', 'ttb', 'btt'.

fonthinting: TTF_HINTING_XXX
Values: 'normal', 'light', 'mono', 'none', 'light subpixel'.

fullscreenmode
Values: 'real', 'fake', 'windowed'.

glattr: SDL_GL_XXX (SDL_GLattr)
Values: 'red size', 'green size', 'blue size', 'alpha size', 'buffer size', 'doublebuffer', 'depth size', 'stencil size', 'accum red size', 'accum green size', 'accum blue size', 'accum alpha size', 'stereo', 'multisamplebuffers', 'multisamplesamples', 'accelerated visual', 'retained backing', 'context major version', 'context minor version', 'context egl', 'context flags', 'context profile mask', 'share with current context', 'framebuffer srgb capable', 'context release behavior', 'context reset notification', 'context no error', 'floatbuffers'.

glprofile: SDL_GL_CONTEXT_PROFILE_XXX (SDL_GLprofile)
Values: 'core', 'compatibility', 'es'.

hapticdirection: SDL_HAPTIC_XXX
Values: 'polar', 'cartesian', 'spherical', 'steering axis'.

haptictype: SDL_HAPTIC_XXX
Values: 'constant', 'sine', 'leftright', 'triangle', 'sawtoothup', 'sawtoothdown', 'ramp', 'spring', 'damper', 'inertia', 'friction', 'custom'.

hatstate: SDL_HAT_XXX
Values: 'centered', 'up', 'right', 'down', 'left', 'rightup', 'rightdown', 'leftup', 'leftdown'.

hintpriority: SDL_HINT_XXX (SDL_HintPriority)
Values: 'default', 'normal', 'override'.

hittestresult: SDL_HITTEST_XXX (SDL_HitTestResult)
Values: 'normal', 'draggable', 'resize topleft', 'resize top', 'resize topright', 'resize right', 'resize bottomright', 'resize bottom', 'resize bottomleft', 'resize left'.

joystickpowerlevel: SDL_JOYSTICK_POWER_XXX (SDL_JoystickPowerLevel)
Values: 'unknown', 'empty', 'low', 'medium', 'full', 'wired'.

joysticktype: SDL_JOYSTICK_TYPE_XXX (SDL_JoystickType)
Values: 'unknown', 'gamecontroller', 'wheel', 'arcade stick', 'flight stick', 'dance pad', 'guitar', 'drum kit', 'arcade pad', 'throttle'.

keystate: SDL_XXX
Values: 'pressed', 'released'.

logcategory: SDL_LOG_CATEGORY_XXX (SDL_LogCategory)
Values: 'application', 'error', 'assert', 'system', 'audio', 'video', 'render', 'input', 'test'.

logpriority: SDL_LOG_PRIORITY_XXX (SDL_LogPriority)
Values: 'verbose', 'debug', 'info', 'warn', 'error', 'critical'.

mousewheeldir: SDL_MOUSEWHEEL_XXX (SDL_MouseWheelDirection)
Values: 'normal', 'flipped'.

musictype: MUS_XXX (Mix_MusicType)
Values: 'none', 'cmd', 'wav', 'mod', 'mid', 'ogg', 'mp3', 'flac', 'opus'.

orientation: SDL_ORIENTATION_XXX (SDL_DisplayOrientation)
Values: 'unknown', 'landscape', 'landscape flipped', 'portrait', 'portrait flipped'.

pixelformat: SDL_PIXELFORMAT_XXX (SDL_PixelFormatEnum)
Values: 'unknown', 'index1lsb', 'index1msb', 'index4lsb', 'index4msb', 'index8', 'rgb332', 'rgb444', 'bgr444', 'rgb555', 'bgr555', 'argb4444', 'rgba4444', 'abgr4444', 'bgra4444', 'argb1555', 'rgba5551', 'abgr1555', 'bgra5551', 'rgb565', 'bgr565', 'rgb24', 'bgr24', 'rgb888', 'rgbx8888', 'bgr888', 'bgrx8888', 'argb8888', 'rgba8888', 'abgr8888', 'bgra8888', 'argb2101010', 'yv12', 'iyuv', 'yuy2', 'uyvy', 'yvyu', 'nv12', 'nv21', 'external oes'.

powerstate: SDL_POWERSTATE_XXX (SDL_PowerState)
Values: 'unknown', 'on battery', 'no battery', 'charging', 'charged'.

rwopstype: SDL_RWOPS_XXX
Values: 'unknown', 'winfile', 'stdfile', 'jnifile', 'memory', 'memory ro'.

rwopswhence: RW_XXX
Values: 'seek set', 'seek cur', 'seek end'.

sensortype = SDL_SENSOR_XXX (SDL_SensorType)
Values: 'invalid', 'unknown', 'accel', 'gyro', or an integer for custom types.

scalemode: SDL_ScaleModeXXX (SDL_ScaleMode)
Values: 'nearest', 'linear', 'best'.

swapinterval
Values: 'immediate', 'vsync', 'adaptive vsync'.

systemcursor: SDL_SYSTEM_CURSOR_XXX (SDL_SystemCursor)
Values: 'arrow', 'ibeam', 'wait', 'crosshair', 'waitarrow', 'sizenwse', 'sizenesw', 'sizewe', 'sizens', 'sizeall', 'no', 'hand'.

textureaccess: SDL_TEXTUREACCESS_XXX (SDL_TextureAccess)
Values: 'static', 'streaming', 'target'.

touchdevicetype: SDL_TOUCH_DEVICE_XXX (SDL_TouchDeviceType)
Values: 'invalid', 'direct', 'indirect absolute', 'indirect relative'.

windoweventtype: SDL_WINDOWEVENT_XXX (SDL_WindowEventID)
Values: 'none', 'shown', 'hidden', 'exposed', 'moved', 'resized', 'size changed', 'minimized', 'maximized', 'restored', 'enter', 'leave', 'focus gained', 'focus lost', 'close', 'take focus', 'hit test', 'iccprof changed', 'display changed'.

Flags

Flags in MoonSDL2 functions and structs are always represented as plain integers, and encoded in the same way as the corresponding flags in the C SDL2 API.

The sdl table contains the SDL_XXX values, renamed as sdl.XXX (e.g. sdl.INIT_TIMER, sdl.INIT_AUDIO, etc.). It also contains the IMG_XXX values from SDL2_image renamed as sdl.IMG_XXX, and similarly for the values from SDL2_ttf and SDL2_mixer.

For each flags type (see the list below), a utility function is also available to map an integer code to a list of string literals, each corresponding to an individual bit set in the code, and viceversa to encode an integer value from the individual bits given as a list of string literals. The generic definition of such functions is the following, where xxxflags stands for initflags, windowflags, etc:

  • code = xxxflags(s1, s2, …​)
    s1, s2, …​ = xxxflags(code)
    Maps the integer code to/from the list of string values s1, s2, …​.

audioallowflags: sdl.AUDIO_ALLOW_XXX
Values: 'frequency change', 'format change', 'channels change', 'samples change', 'any change'.

flipflags: sdl.FLIP_XXX (SDL_RendererFlip)
Values: 'none', 'horizontal', 'vertical'.

glcontextflags: sdl.SDL_GL_CONTEXT_XXX_FLAG (SDL_GLcontextFlag)
Values: 'debug', 'forward compatible', 'robust access', 'reset isolation'.

imginitflags: sdl.IMG_INIT_XXX (IMG_InitFlags)
Values: 'jpg', 'png', 'tif', 'webp', 'jxl', 'avif'.

initflags: sdl.INIT_XXX
Values: 'timer', 'audio', 'video', 'joystick', 'haptic', 'gamecontroller', 'events', 'sensor', 'noparachute', 'everything'.

messageboxbuttonflags: sdl.MESSAGEBOX_BUTTON_XXX (SDL_MessageBoxButtonFlags)
Values: 'returnkey default', 'escapekey default'.

messageboxflags: sdl.MESSAGEBOX_XXX (SDL_MessageBoxFlags)
Values: 'error', 'warning', 'information', 'buttons left to right', 'buttons right to left'.

mixinitflags: sdl.MIX_INIT_XXX (MIX_InitFlags)
Values: 'flac', 'mod', 'mp3', 'ogg', 'mid', 'opus'.

rendererflags: sdl.RENDERER_XXX (SDL_RendererFlags)
Values: 'software', 'accelerated', 'presentvsync', 'targettexture'.

ttfstyleflags: sdl.TTF_STYLE_XXX
Values: 'normal', 'bold', 'italic', 'underline', 'strikethrough'.

windowflags: sdl.WINDOW_XXX (SDL_WindowFlags)
Values: 'fullscreen', 'opengl', 'shown', 'hidden', 'borderless', 'resizable', 'minimized', 'maximized', 'mouse grabbed', 'input focus', 'mouse focus', 'fullscreen desktop', 'foreign', 'allow highdpi', 'mouse capture', 'always on top', 'skip taskbar', 'utility', 'tooltip', 'popup menu', 'keyboard grabbed', 'vulkan', 'metal', 'input grabbed'.


1. This manual is written in AsciiDoc, rendered with AsciiDoctor and a CSS from the AsciiDoctor Stylesheet Factory.
2. Objects are anchored to the Lua registry at their creation, so even if the script does not have references to an object, a reference always exists on the registry and this prevents the GC to collect it.
3. It is good practice to not leave invalid references to objects around, because they prevent the GC to collect the memory associated with the userdata.