Note: The documentation has now been imported to a GitHub wiki at https://github.com/Tangent128/luasdl2/wiki; use that, as this page will likely drift out of date.


Lua-SDL2

Welcome to Lua-SDL2!

About

Lua-SDL2 is an SDL 2 binding for Lua. It is released under the ISC license.

Versioning

Lua-SDL2 uses the same versioning as SDL except that it adds a trailing -v where v is the binding version (e.g 2.0.3-4 is SDL 2.0.3 and binding version 4).

Download

To obtain the Lua-SDL2 sources:

(Precompiled binaries are not available at present.)

Releases

Release tarballs can be downloaded from Github.

Development version

The latest version of the code may be checked out via git:

$ git clone https://github.com/Tangent128/luasdl2.git

Note that the development version's stability can very heavily from commit to commit. Some revisions may be obviously buggy, others might be stabler than the previous release. Don't rely on them for production.

Documentation

Tutorials

Versions


Documentation Index

API Reference

The following categories are the available group of SDL functions. They all belong to the SDL module.

Module

local SDL = require "SDL" 

Categories

Basics

Category Description
Initialization Initialize SDL and its modules
Errors Error management and reporting
Logging Logging functions
Hints Hints

Video and display

Category Description
Display Display management
Window Window management
Texture Texture creation and manipulation
Surface Surface object
Renderer Renderer management
GL OpenGL management

System and filesystem

Category Description
Platform Platform inspection
Power Power management
RWops Portable file management
Filesystem File system

Threading

Category Description
Threads Threads
Channels Per thread messages
Timer Timers

Audio

Category Description
Audio Audio management

Input and events

Category Description
Events General events functions
Mouse Mouse handling
Keyboard Keyboard handling and input
Joystick Joystick input
Haptic Force feedback support

Geometry and basic types

Category Description
Rectangle How to manage SDL_Rect
Color How to deal with colors
Point How to use points
Line Line management

Building from sources

Lua-SDL2 installation guide.

Requirements

And optional libraries for the official SDL modules:

Installation

Take care to substitute version with the current Lua-SDL2 version.

$ tar xvzf Lua-SDL2-version.tar.gz
$ cd Lua-SDL2-version
$ mkdir _build_
$ cd _build_
$ cmake ..
$ make
# make install

Customizing the build

Several options are available. The following commands are expected to be ran in the build directory created above.

Disable SDL_mixer

$ cmake .. -DWITH_MIXER=Off

Disable SDL_ttf

$ cmake .. -DWITH_TTF=Off

Disable SDL_net

$ cmake .. -DWITH_NET=Off

Disable SDL_image

$ cmake .. -DWITH_IMAGE=Off

Disable installation of examples

$ cmake .. -DWITH_DOCS=Off

Change the installation path of libraries

$ cmake .. -DLUA_LIBDIR=/path/to/install/libraries

Note that this is relative to CMAKE_INSTALL_PREFIX.

Change the installation directory of examples

$ cmake .. -DWITH_DOCSDIR=/path/to/install/examples

Note that this is relative to CMAKE_INSTALL_PREFIX.

Changing the Lua version

You can change the Lua version by setting the WITH_LUAVER CMake variable; supported values are:

$ cmake .. -DWITH_LUAVER=JIT

It is sometimes useful to explicitly specify the path to the selected Lua version's include and library directories. The variables to set depend on the configured version:

$ cmake .. -DWITH_LUAVER=53 -DLUA53_INCLUDE_DIR=/path/to/headers/
$ cmake .. -DWITH_LUAVER=52 -DLUA52_INCLUDE_DIR=/path/to/headers/
$ cmake .. -DWITH_LUAVER=51 -DLUA_INCLUDE_DIR=/path/to/headers/
$ cmake .. -DWITH_LUAVER=JIT -DLUAJIT_INCLUDE_DIR=/path/to/headers/

Also note that the include directory should be the one directly containing the headers. We #include <lua.h>, not #include <lua/lua.h>.


image.flags

Flags for initializing SDL_image.

Enum

SYNOPSIS

image.flags = {
    JPG,
    PNG,
    TIF
}

VALUES


image.init

Initialize SDL_image module.

Function

SYNOPSIS

flags, ret, err = function image.init(flags)

ARGUMENTS

RETURNS


image.is

Check if the image is a certain type.

Function

SYNOPSIS

ret, err = function image.is(rwops, name)

ARGUMENTS

RETURNS


image.load

Load an image a surface from a file.

Function

SYNOPSIS

s, err = function image.load(path)

ARGUMENTS

RETURNS


image.load_RW

Load an image a surface from a RWops.

Function

SYNOPSIS

s, err = function image.load(rwops, name)

ARGUMENTS

RETURNS


image.quit

Close the module.

Function

SYNOPSIS

function image.quit()

Implementation notes

Lua-SDL2 is implemented in pure C without any Lua code. It should runs on major platforms that supports at least ANSI C and some addons.

Lua-SDL2 has been tested on the following platforms:


Major differences with official C API

Lua-SDL2 has some differences with the official SDL-2.0 C API.

First, it uses object orientation for many structures. But some limitations of Lua also needs to implement the binding differently.


Chunk:fadeInChannel

Gradually fade in the chunk.

Method

SYNOPSIS

ret, err = function Chunk:fadeInChannel(channel, loops, delay, ticks)

ARGUMENTS

RETURNS


Chunk

The Mix_Chunk wrapper.

Object

Methods

Method Description
Chunk:volume Play the chunk
Chunk:playChannel Play in a channel
Chunk:fadeInChannel Fade in gradually in a channel

Chunk:playChannel

Play the chunk on a channel.

Method

SYNOPSIS

ret, err = function Chunk:playChannel(channel, loops, ticks)

ARGUMENTS

RETURNS


Chunk:volume

Set the chunk volume.

Method

SYNOPSIS

vol = function Chunk:volume(vol)

ARGUMENTS

RETURNS


mixer.fading

Fading status.

Enum

SYNOPSIS

mixer.fading = {
    None,
    Out,
    In
}

VALUES


mixer.flags

Flags for SDL_mixer initialization.

Enum

SYNOPSIS

mixer.flags = {
    FLAC,
    OGG,
    MOD,
    MP3
}

VALUES


Music:fadeIn

Fade in gradually.

Method

SYNOPSIS

ret, err = function Music:fadeIn(loops, delay, position)

ARGUMENTS

RETURNS


Music:fadeOut

Fade out gradually.

Method

SYNOPSIS

ret, err = function Music:fadeOut(delay)

ARGUMENTS

RETURNS


Music:fading

Get the music fading status.

Method

SYNOPSIS

status = function Music:fading()

RETURNS


Music:getType

Get the music type.

Method

SYNOPSIS

type = function Music:getType()

RETURNS


Music:halt

Halt the music.

Method

SYNOPSIS

function Music:halt()

Music

The Mix_Music object wrapper.

Object

Methods

Method Description
Music:play Play the music
Music:fadeIn Fade in gradually
Music:volume Set the volume
Music:resume Resume the music
Music:rewind Rewind
Music:setPosition Set the position
Music:halt Stop the music
Music:fadeOut Fade out gradually
Music:getType Get the music type
Music:paused Check if paused
Music:playing Check if playing
Music:fading Get the fading status

Music:paused

Check if the music is paused.

Method

SYNOPSIS

status = function Music:paused()

RETURNS


Music:play

Play the music.

Method

SYNOPSIS

ret, err = function Music:play(loops)

ARGUMENTS

RETURNS


Music:playing

Check if the music is playing.

Method

SYNOPSIS

status = function Music:playing()

RETURNS


Music:resume

Resume a paused music.

Method

SYNOPSIS

function Music:resume()

Music:rewind

Rewind the music.

Method

SYNOPSIS

function Music:rewind()

Music:setPosition

Set the music position.

Method

SYNOPSIS

ret, err = function Music:setPosition(pos)

ARGUMENTS

RETURNS


Music:volume

Set the music volume.

Method

SYNOPSIS

vol = function Music:volume(vol)

ARGUMENTS

RETURNS


mixer.type

Music type.

Enum

SYNOPSIS

mixer.type = {
    None,
    WAV,
    MOD,
    MID,
    MP3,
    OGG
}

VALUES


mixer.allocateChannels

Allocate channels.

Function

SYNOPSIS

n = function mixer.allocateChannels(n)

ARGUMENTS

RETURNS


mixer.closeAudio

Close the audio.

Function

SYNOPSIS

function mixer.closeAudio()

mixer.expireChannel

Halt a channel after a delay.

Function

SYNOPSIS

n = function mixer.expireChannel(channel, delay)

ARGUMENTS

RETURNS


mixer.fadeOutChannel

Fade out some channels.

Function

SYNOPSIS

n = function mixer.fadeOutSomeChannels(channel, delay)

ARGUMENTS

RETURNS


mixer.fadeOutGroup

Fade out a group progressively.

Function

SYNOPSIS

count = function mixer.fadeOutGroup(tag, delay)

ARGUMENTS

RETURNS


mixer.fadingChannel

Check the fading status.

Function

SYNOPSIS

status = function mixer.fadingChannel(channel)

ARGUMENTS

RETURNS


mixer.getChunkDecoder

Get a chunk decoder name.

Function

SYNOPSIS

name = function mixer.getChunkDecoder(index)

ARGUMENTS

RETURNS


mixer.getMusicDecoder

Get a music decoder name.

Function

SYNOPSIS

name = function mixer.getMusicDecoder(index)

ARGUMENTS

RETURNS


mixer.getNumChunkDecoders

Get the number of chunk decoders.

Function

SYNOPSIS

n = function mixer.getNumChunkDecoders()

RETURNS


mixer.getNumMusicDecoders

Get the number of music decoders.

Function

SYNOPSIS

num = function mixer.getNumMusicDecoders()

RETURNS


mixer.groupAvailable

Get the first channel available.

Function

SYNOPSIS

channel = function mixer.groupAvailable(tag)

ARGUMENTS

RETURNS


mixer.groupChannel

Group a channel.

Function

SYNOPSIS

ret = function mixer.groupChannel(channel, tag)

ARGUMENTS

RETURNS


mixer.groupChannels

Group several channels.

Function

SYNOPSIS

n = function mixer.groupChannels(from, to, tag)

ARGUMENTS

RETURNS


mixer.groupCount

Get the number of channels in the group.

Function

SYNOPSIS

n = function mixer.groupCount(tag)

ARGUMENTS

RETURNS


mixer.groupNewer

Find the newest channel actively playing.

Function

SYNOPSIS

channel = function mixer.groupNewer(tag)

ARGUMENTS

RETURNS


mixer.groupOldest

Find the oldest channel actively playing.

Function

SYNOPSIS

channel = function mixer.groupOldest(tag)

ARGUMENTS

RETURNS


mixer.haltChannel

Halt a channel.

Function

SYNOPSIS

ret = function mixer.haltChannel(channel)

ARGUMENTS

RETURNS


mixer.haltGroup

Halt a group.

Function

SYNOPSIS

count = function mixer.fadeOutGroup(tag)

ARGUMENTS

RETURNS


mixer.init

Initialize the module.

Function

SYNOPSIS

flags, ret, err = function mixer.init(flags)

ARGUMENTS

RETURNS


mixer.loadMUS

Load a music by path.

Function

SYNOPSIS

music, err = function mixer.loadMUS(path)

ARGUMENTS

RETURNS


mixer.loadWAV

Load a wav file as a chunk.

Function

SYNOPSIS

chunk, err = function mixer.loadWAV(path)

ARGUMENTS

RETURNS


mixer.loadWAV_RW

Load a chunk from a RWops.

Function

SYNOPSIS

chunk,err = function mixer.loadWAV_RW(rw)

ARGUMENTS

RETURNS


mixer.openAudio

Open the audio system.

Function

SYNOPSIS

ret, err = function mixer.openAudio(frequency, format, channels, chunksize)

ARGUMENTS

RETURNS


mixer.pause

Pause some channels.

Function

SYNOPSIS

function mixer.pause(channel)

ARGUMENTS


mixer.paused

Check how many channels are paused.

Function

SYNOPSIS

ret = function mixer.paused(channel)

ARGUMENTS

RETURNS


mixer.playing

Check how many channels are playing.

Function

SYNOPSIS

ret = function mixer.playing(channel)

ARGUMENTS

RETURNS


mixer.quit

Quit the audio subsystem.

Function

SYNOPSIS

function mixer.quit()

mixer.reserveChannels

Reserve some channels.

Function

SYNOPSIS

n = function mixer.reserveChannels(count)

ARGUMENTS

RETURNS


mixer.resume

Resume some channels

Function

SYNOPSIS

function mixer.resume(channel)

ARGUMENTS


mixer.volume

Set the volume

Function

SYNOPSIS

volume = function mixer.volume(channel, volume)

ARGUMENTS

RETURNS


IpAddress

The IP address definition

Table

SYNOPSIS

local address = {
    host,
    port
}

FIELDS


Set

Object wrapper for SDLNet_SocketSet.

Object

Methods

Method Description
Set:add Add a socket for input
Set:del Remove a socket from the set
Set:checkSockets Wait a socket for being ready

Set:add

Add a socket to the set.

Note: This function will reference the socket in the registry and will not be garbage collected if the owner of the socket delete it. The reference will be removed when the set is destroyed or when the user remove the reference using Set:del.

Method

SYNOPSIS

length, err = function Set:add(s)

ARGUMENTS

RETURNS


Set:checkSockets

Wait for sockets to be ready.

Method

SYNOPSIS

n = function Set:checkSockets(timeout)

ARGUMENTS

RETURNS


Set:del

Remove a socket from the set. The set will not own the socket anymore.

Method

SYNOPSIS

length, err = function Set:del(s)

ARGUMENTS

RETURNS


TcpSocket:accept

Accept a socket.

Method

SYNOPSIS

s, err = function TcpSocket:accept()

RETURNS


TcpSocket:close

Close the socket.

Method

SYNOPSIS

function TcpSocket:close()

TcpSocket:getPeerAddress

Get the peer address.

Method

SYNOPSIS

address, err = function TcpSocket:getPeerAddress()

RETURNS


TcpSocket

Object wrapping the TCPsocket.

Object

Methods

Method Description
TcpSocket:close Close the socket
TcpSocket:accept Accept a socket
TcpSocket:getPeerAddress Get the peer address
TcpSocket:send Send some data
TcpSocket:recv Receive some data
TcpSocket:ready Check if the socket is ready

TcpSocket:ready

Check if the socket is ready.

Method

SYNOPSIS

state = function TcpSocket:ready()

RETURNS


TcpSocket:recv

Receive some data.

Method

SYNOPSIS

str, length, err = function TcpSocket:recv(count)

ARGUMENTS

RETURNS


TcpSocket:send

Send some data.

Method

SYNOPSIS

sent, err = function TcpSocket:send(data)

ARGUMENTS

RETURNS


UdpSocket:bind

Bind the socket to an address.

Method

SYNOPSIS

channel, err = function UdpSocket:bind(channel, address)

ARGUMENTS

RETURNS


UdpSocket:close

Close the socket.

Method

SYNOPSIS

function UdpSocket:close()

UdpSocket:getPeerAddress

Get the peer address.

Method

SYNOPSIS

address, err = function UdpSocket:getPeerAddress()

RETURNS


UdpSocket

Object wrapping the UDPsocket.

Object

Methods

Method Description
UdpSocket:close Close the socket
UdpSocket:bind Bind the socket
UdpSocket:unbind Unbind the socket
UdpSocket:getPeerAddress Get the peer address
UdpSocket:send Send some data
UdpSocket:recv Receive some data
UdpSocket:ready Check if the socket is ready

UdpSocket:ready

Check if the socket is ready.

Method

SYNOPSIS

state = function UdpSocket:ready()

RETURNS


UdpSocket:recv

Receive some data.

Method

SYNOPSIS

str, length, err = function UdpSocket:recv()

RETURNS


UdpSocket:send

Send some data using a channel.

Method

SYNOPSIS

n, err = function UdpSocket:send(data, channel)

ARGUMENTS

RETURNS

UdpSocket:send

Send some data using an address.

Method

SYNOPSIS

n, err = function UdpSocket:send(data, address)

ARGUMENTS

RETURNS


UdpSocket:unbind

Unbind the socket.

Method

SYNOPSIS

function UdpSocket:unbind(channel)

ARGUMENTS


net.init

Initialize the SDL_net module.

Function

SYNOPSIS

ret, err = function net.init()

RETURNS


net.openTcp

Create a TCP object.

Function

SYNOPSIS

s, err = function net.openTcp(address)

ARGUMENTS

RETURNS


net.openUdp

Create a UDP object.

Function

SYNOPSIS

s, err = function net.openUdp(port)

ARGUMENTS

RETURNS


net.quit

Close the module.

Function

SYNOPSIS

function net.quit()

net.resolveHost

Resolve an hostname.

Function

SYNOPSIS

address, err = function net.resolveHost(host, port)

ARGUMENTS

RETURNS


net.resolveIp

Resolve the host address from an IpAddress.

Function

SYNOPSIS

host, err = function net.resolveIp(address)

ARGUMENTS

RETURNS


net.set

Create a new socket set.

Function

SYNOPSIS

set, err = function net.set(max)

ARGUMENTS

RETURNS


SDL image

Additional module for SDL_image.

Module

local image = require "SDL.image" 

Tables

Table Description
image.flags Flags for initialization

Functions

Function Description
image.init Initialize SDL_image
image.quit Quit the module
image.load Load an image from a path
image.load_RW Load an image from a RWops
image.is Check if an image is a certain type

SDL mixer

Additional module for SDL_mixer.

Module

local mixer = require "SDL.mixer" 

Objects

Object Description
Music A music object
Chunk A chunk object

Tables

Table Description
mixer.flags Flags for mixer
mixer.fading Fading status
mixer.type Type of music

Functions

Function Description
mixer.init Initialize the SDL_mixer module
mixer.openAudio Open an audio device
mixer.getNumChunkDecoders Get the number of decoders
mixer.getChunkDecoder Get a chunk decoder name
mixer.loadWAV Load a chunk by path
mixer.loadWAV_RW Load a chunk with RWops
mixer.allocateChannels Prepare channels
mixer.volume Set or get the volume
mixer.pause Pause the sound system
mixer.resume Resume the sound
mixer.haltChannel Halt a channel
mixer.expireChannel Expire a channel
mixer.fadeOutChannel Fade out effect
mixer.playing Check if playing
mixer.paused Check if paused
mixer.fadingChannel Get the fading status
mixer.reserveChannels Reserve channels
mixer.groupChannel Group channel
mixer.groupChannels Group channels
mixer.groupCount Get the number of channels in a group
mixer.groupAvailable Find a channel in a group
mixer.groupOldest Get the oldest channel
mixer.groupNewer Get the newest channel
mixer.fadeOutGroup Fade out a group
mixer.haltGroup Halt a group
mixer.getNumMusicDecoders Get the number of music decoders
mixer.getMusicDecoder Get a music decoder name
mixer.loadMUS Load a music
mixer.closeAudio Close the audio
mixer.quit Close the SDL_mixer module

SDL net

Additional module for SDL_net.

Module

local net = require "SDL.net" 

Types

Type Description
IpAddress An internet IP address definition

Objects

Object Description
Set A set of sockets
UdpSocket A UDP socket
TcpSocket A TCP socket

Functions

Function Description
net.init Initialize the module
net.resolveHost Resolve a hostname
net.resolveIp Resolve an ip address
net.set Create a new set
net.openTcp Create a TCP socket
net.openUdp Create a UDP socket
net.quit Close the module

SDL ttf

Additional module for SDL_ttf.

Module

local ttf = require "SDL.ttf" 

Objects

Object Description
Font Font object that maps TTF_Font

Tables

Table Description
ttf.fontStyle Font style rendering
ttf.fontHinting Font hinting

Functions

Function Description
ttf.init Initialize the module
ttf.open Open a font
ttf.quit Close the module

AudioCallback

The audio callback is used to play sound. It is called by the SDL internal code at a specific interval. Because it runs in a different thread, it also require to be ran in a different Lua state.

That is, to facilitate the audio process, only a file as a callback is currently allowed. This file must return a function to be called everytime the SDL needs to play audio.

Function

SYNOPSIS

stream = function callback(length)

ARGUMENTS

RETURNS

EXAMPLE


AudioDevice

The audio device object.

Object

Methods

Method Description
AudioDevice:close Close the device
AudioDevice:pause Pause the device
AudioDevice:lock Lock the device
AudioDevice:status Get the audio device status
AudioDevice:unlock Unlock the audio device

AudioDevice:close

Close the device.

Method

SYNOPSIS

function AudioDevice:close()

AudioDevice:lock

Lock the audio device.

Method

SYNOPSIS

function AudioDevice:lock()

AudioDevice:pause

Pause the audio device.

Method

SYNOPSIS

function AudioDevice:pause(mode)

ARGUMENTS


AudioDevice:status

Get the audio status.

Method

SYNOPSIS

status = function AudioDevice:status()

RETURNS


AudioDevice:unlock

Unlock the audio device.

Method

SYNOPSIS

function AudioDevice:unlock()

SDL.audioFormat

The SDL audio format.

Enum

SYNOPSIS

SDL.audioFormat = {
    S8,
    U8,
    S16LSB,
    S16MSB,
    S16SYS,
    S16,
    U16LSB,
    U16MSB,
    U16SYS,
    U16,
    S32LSB,
    S32MSB,
    S32SYS,
    S32,
    F32LSB,
    F32MSB,
    F32SYS,
    F32
}

VALUES


SDL.audioStatus

The audio status.

Enum

SYNOPSIS

SDL.audioStatus = {
    Stopped,
    Playing,
    Paused
}

VALUES


SDL.blendMode

Enumeration for blend mode.

Enum

SYNOPSIS

SDL.blendMode = {
    None,
    Blend,
    Add,
    Mod
}

VALUES


Channel:clear

Remove all the values from the channel.

Method

SYNOPSIS

function Channel:clear()

Channel:first

Get the first value.

Note: this function does not pop the value.

Method

SYNOPSIS

value = function Channel:first()

RETURNS


Channel:last

Get the last value.

Note: this function does not pop the value.

Method

SYNOPSIS

value = function Channel:last()

RETURNS


Channel

The channel object. Every of these functions are thread safe.

Methods

Method Description
Channel:first Peek the first value
Channel:last Peek the last value
Channel:push Push a value
Channel:supply Supply a value and wait a thread to accept it
Channel:wait Wait for a value to be supplied
Channel:pop Remove the head value
Channel:clear Remove all values from the channel

Channel:pop

Pop the first value.

Method

SYNOPSIS

function Channel:pop()

Channel:push

Push a value to the queue. This function also signals the arrival of the value to waiting threads.

Method

SYNOPSIS

ret, err = function Channel:push(value)

ARGUMENTS

RETURNS


Channel:supply

Works like Channel:push except that waits indefinitely until a thread get the value.

Method

SYNOPSIS

ret, err = function Channel:supply(value)

ARGUMENTS

RETURNS


Channel:wait

Wait indefinitely for a value to be supplied using Channel:supply.

Note: this function does not pop the value.

Method

SYNOPSIS

value = function Channel:wait()

RETURNS


Color (hexadecimal)

Color definition as an hexadecimal number.

Type

SYNOPSIS

local c = 0xAABBCC

EXAMPLE

local c = 0xef1cb3

Color (table)

Color definition as a table.

Table

SYNOPSIS

local c = {
    r, g, b
}

FIELDS

EXAMPLE

local c = {
    r = 60,
    g = 40,
    b = 100
}

Colors

A sequence of color. The sequence can safely mix tables and hexadecimal values.

Table

SYNOPSIS

local sequence = {
    c1, c2, ..., cn
}

FIELDS

EXAMPLE

local colors = { { r = 10, g = 10, b = 60 }, 0xffbbcc }

Context

This an opaque object used by many several functions. It does not have any methods.


DisplayMode

A table used for handling display modes.

Table

SYNOPSIS

local displaymode = {
    w,
    h,
    format,
    refreshRate
}

FIELDS


SDL.eventAction

Action to do.

Enum

SYNOPSIS

SDL.eventAction = {
    Add,
    Peek,
    Get
}

VALUES


Event

This is the table used for handling events. Fields are dynamically set depending on the type of event.

Table

SYNOPSIS

local event = {
    type,
    ...
}

FIELDS

WindowEvent

KeyDown, KeyUp

TextEditing

TextInput

MouseMotion

MouseButtonDown, MouseButtonUp

MouseWheel

JoyAxisMotion

JoyBallMotion

JoyHatMotion

JoyButtonDown, JoyButtonUp

JoyDeviceAdded, JoyDeviceRemoved


SDL.event

Type of event.

Enum

SYNOPSIS

SDL.event = {
    First,
    Quit,
    AppTerminating,
    AppLowMemory,
    AppWillEnterBackground,
    AppDidEnterBackground,
    AppWillEnterForeground,
    AppDidEnterForeground,
    WindowEvent,
    KeyDown,
    KeyUp,
    TextEditing,
    TextInput,
    MouseMotion,
    MouseButtonDown,
    MouseButtonUp,
    MouseWheel,
    JoyAxisMotion,
    JoyBallMotion,
    JoyHatMotion,
    JoyButtonDown,
    JoyButtonUp,
    JoyDeviceAdded,
    JoyDeviceRemoved,
    ControllerAxisMotion,
    ControllerButtonDown,
    ControllerButtonUp,
    ControllerDeviceAdded,
    ControllerDeviceRemoved,
    ControllerDeviceRemapped,
    FingerDown,
    FingerUp,
    FingerMotion,
    DollarGesture,
    DollarRecord,
    MultiGesture,
    ClipboardUpdate,
    DropFile,
    UserEvent,
    Last,
}

VALUES


SDL.eventWindow

Window event.

Enum

SYNOPSIS

SDL.eventWindow = {
    Shown,
    Hidden,
    Exposed,
    Moved,
    Resized,
    SizeChanged,
    Minimized,
    Maximized,
    Restored,
    Enter,
    Leave,
    FocusGained,
    FocusLost,
    Close
}

VALUES


Filter

The filter object.

Object

Methods

Method Description
Filter:remove Remove the filter

Filter:remove

Remove the filter and its SDL callback. This function is also called when the object is collected.

Method

SYNOPSIS

function Filter:remove()

SDL.glAttr

OpenGL attributes.

Enum

SYNOPSIS

SDL.glAttr = {
    RedSize,
    GreenSize,
    BlueSize,
    AlphaSize,
    BufferSize,
    DoubleBuffer,
    DepthSize,
    StencilSize,
    AccumRedSize,
    AccumGreenSize,
    AccumBlueSize,
    AccumAlphaSize,
    Stereo,
    MultiSampleBuffers,
    MultiSampleSamples,
    AcceleratedVisual,
    RetainedBacking,
    ContextMajorVersion,
    ContextMinorVersion,
    ContextEGL,
    ContextFlags,
    ContextProfileMask,
    ShareWithCurrentContext,
    FramebufferSRGBCapable
}

VALUES


SDL.glFlags

OpenGL flags.

Enum

SYNOPSIS

SDL.glFlags = {
    Debug,
    ForwardCompatible,
    RobustAccess,
    ResetIsolation
}

VALUES


SDL.glProfile

OpenGL profile

Enum

SYNOPSIS

SDL.glProfile = {
    Core,
    Compatibility,
    ES
}

VALUES


Haptic:destroyEffect

Destroy the effect.

Method

SYNOPSIS

function Haptic:destroyEffect(effect)

ARGUMENTS


SDL.hapticDirection

The haptic direction.

Enum

SYNOPSIS

SDL.hapticDirection = {
    Polar,
    Cartesian,
    Spherical
}

VALUES


HapticDirectionType

The mapping of SDL_HapticDirection.

Table

SYNOPSIS

local direction = {
    type
    directions = { }
}

FIELDS


HapticEffect

The effect description. The table is used for every effect type defined in SDL.hapticType.

Table

SYNOPSIS

local effect = {
    type
    ...

FIELDS

Constant

Sine, Square, Triangle, SawToothUp, SawToothDown

Spring, Damper, Inertia, Friction

Ramp

LeftRight


Haptic:effectSupported

Check if an effect is supported.

Method

SYNOPSIS

ret, err = function Haptic:effectSupported(effect)

ARGUMENTS

RETURNS


Haptic:getEffectStatus

Get the effect status.

Method

SYNOPSIS

status = function Haptic:getEffect(effect)

ARGUMENTS

RETURNS


Haptic:index

Get the haptic index.

Method

SYNOPSIS

index = function Haptic:index()

RETURNS


Haptic:newEffect

Add a new effect.

Method

SYNOPSIS

id, err = function Haptic:newEffect(effect)

ARGUMENTS

RETURNS


Haptic:numAxes

Get the number of axes.

Method

SYNOPSIS

n, err = function Haptic:numAxes()

RETURNS


Haptic:numEffects

Get the number of effects.

Method

SYNOPSIS

n, err = function Haptic:numEffects()

RETURNS


Haptic:numEffectsPlaying

Get the number of effects playing.

Method

SYNOPSIS

n, err = function Haptic:numEffectsPlaying()

RETURNS


Haptic

The haptic object.

Object

Methods

Method Description
Haptic:destroyEffect Destroy an effect
Haptic:effectSupported Check if an effect is supported
Haptic:getEffectStatus Get the effect status
Haptic:index Get the haptic index
Haptic:newEffect Create a new effect
Haptic:numAxes Get the number of axes
Haptic:numEffects Get the number of effects
Haptic:numEffectsPlaying Get the number of effects playing
Haptic:pause Pause the haptic
Haptic:rumbleInit Init the rumble
Haptic:rumblePlay Play the rumble
Haptic:rumbleStop Stop the rumble
Haptic:rumbleSupported Check if rumble is supported
Haptic:runEffect Run an effect
Haptic:setAutocenter Set the autocenter flag
Haptic:setGain Set the gain value
Haptic:stopAll Stop all effects
Haptic:stopEffect Stop an effect
Haptic:unpause Unpause
Haptic:updateEffect Update effect

Haptic:pause()

Pause the device.

Method

SYNOPSIS

ret, err = function Haptic:pause()

RETURNS


Haptic:rumbleInit

Rumble initialization.

Method

SYNOPSIS

ret, err = function Haptic:rumbleInit()

RETURNS


Haptic:rumblePlay

Play the rumble.

Method

SYNOPSIS

ret, err = function Haptic:rumblePlay(strength, length)

ARGUMENTS

RETURNS


Haptic:rumbleStop

Stop the rumble.

Method

SYNOPSIS

ret, err = function Haptic:rumbleStop()

RETURNS


Haptic:rumbleSupported

Check if rumble is supported.

Method

SYNOPSIS

ret, err = function Haptic:rumbleSupported()

RETURNS


Haptic:runEffect

Run an effect.

Method

SYNOPSIS

ret, err = function Haptic:runEffect(id, iterations)

ARGUMENTS

RETURNS


Haptic:setAutocenter

Set to auto center.

Method

SYNOPSIS

ret, err = function Haptic:setAutocenter(value)

ARGUMENTS

RETURNS


Haptic:setGain

Set the gain value.

Method

SYNOPSIS

ret, err = function Haptic:setGain(value)

ARGUMENTS

RETURNS


Haptic:stopAll

Stop all effects.

Method

SYNOPSIS

ret, err = function Haptic:stopAll()

RETURNS


Haptic:stopEffect

Stop an effect.

Method

SYNOPSIS

ret, err = function Haptic:stopEffect(id)

ARGUMENTS

RETURNS


SDL.hapticType

The haptic type.

Enum

SYNOPSIS

SDL.hapticType = {
    Constant,
    Sine,
    Square,            -- only if SDL_HAPTIC_SQUARE is defined in the SDL_haptic.h file!
    Triangle,
    SawToothUp,
    SawToothDown,
    Spring,
    Damper,
    Inertia,
    Friction,
    Ramp,
    LeftRight,
    Custom
}

VALUES


Haptic:unpause

Unpause the haptic device.

Method

SYNOPSIS

ret, err = function Haptic:unpause()

RETURNS


Haptic:updateEffect

Update an existing effect.

Method

SYNOPSIS

ret, err = function Haptic:updateEffect(id, e)

ARGUMENTS

RETURNS


SDL.hintPriority

An enumeration of hint priorities.

Enum

SYNOPSIS

SDL.hintPriority = {
    Default,
    Normal,
    Override
}

VALUES


SDL.flags

Enumeration table used for SDL.init.

Table (enumeration)

SYNOPSIS

SDL.flags = {
    Audio,
    Events,
    Everything,
    GameController,
    Haptic,
    Joystick,
    NoParachute,
    Video
}

VALUES

EXAMPLES

local ret, err = SDL.init { SDL.init.Audio, SDL.init.Joystick }

if not ret then
    error(err)
end

SEE ALSO

SDL.init


Joystick:getAttached

Get the attach status.

Method

SYNOPSIS

ret, err = function Joystick:getAttached()

RETURNS


Joystick:getAxis

Get an axis value.

Function

SYNOPSIS

value = function Joystick:getAxis(axis)

ARGUMENTS

RETURNS


Joystick:getBall

Get the ball position.

Method

SYNOPSIS

x, y, err = function Joystick:getBall(ball)

ARGUMENTS

RETURNS


Joystick:getButton

Get the button state.

Method

SYNOPSIS

state = function Joystick:getButton(which)

ARGUMENTS

RETURNS


Joystick:getHat

Get the hat position value.

Method

SYNOPSIS

value = function Joystick:getHat(which)

ARGUMENTS

RETURNS


SDL.joyHat

The position of the hat value in joysticks.

Enum

SYNOPSIS

SDL.joyHat = {
    Left,
    LeftUp,
    Up,
    RightUp,
    Right,
    RightDown,
    Down,
    LeftDown
}

VALUES


Joystick:instanceID

Get the joystick instance id.

Method

SYNOPSIS

id = function Joystick:instanceID()

RETURNS


Joystick:name

Get the joystick name.

Method

SYNOPSIS

name, err = function Joystick:name()

RETURNS


Joystick:numAxes

Get the number of axes.

Method

SYNOPSIS

num, err = function Joystick:numAxes()

RETURNS


Joystick:numBalls

Get the number of balls.

Method

SYNOPSIS

num, err = function Joystick:numBalls()

RETURNS


Joystick:numButtons

Get the number of buttons.

Method

SYNOPSIS

num, err = function Joystick:numButtons()

RETURNS


Joystick:numHats

Get the number of axes.

Method

SYNOPSIS

num, err = function Joystick:numHats()

RETURNS


Joystick

The joystick object mapped from the type SDL_Joystick and its related functions.

Object

Methods

Method Description
Joystick:getAttached Get the joystick status
Joystick:getAxis Get the axis value
Joystick:getBall Get the ball value
Joystick:getButton Get the button value
Joystick:getHat Get the hat value
Joystick:instanceID Get the id
Joystick:name Get the joystick name
Joystick:numAxes Get the number of axes
Joystick:numBalls Get the number of balls
Joystick:numButtons Get the number of buttons
Joystick:numHats Get the number of hats

SDL.key

Enumeration for keys.

Enum

SYNOPSIS

SDL.key = {
    Unknown,
    Return,
    Escape,
    Backspace,
    Tab,
    Space,
    Exclaim,
    Quotedbl,
    Hash,
    Percent,
    Dollar,
    Ampersand,
    Quote,
    LeftParen,
    RightParen,
    Asterisk,
    Plus,
    Comma,
    Minus,
    Period,
    Slash,
    0,
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
    Colon,
    Semicolon,
    Less,
    Equals,
    Greater,
    Question,
    At,
    LeftBracked,
    Backslash,
    RightBracket,
    Caret,
    Underscore,
    Backquote,
    a,
    b,
    c,
    d,
    e,
    f,
    g,
    h,
    i,
    j,
    k,
    l,
    m,
    n,
    o,
    p,
    q,
    r,
    s,
    t,
    u,
    v,
    w,
    x,
    y,
    z,
    Capslock,
    F1,
    F2,
    F3,
    F4,
    F5,
    F6,
    F7,
    F8,
    F9,
    F10,
    F11,
    F11,
    Printscreen,
    ScrollLock,
    Pause,
    Insert,
    Home,
    PageUp,
    Delete,
    End,
    PageDown,
    Right,
    Left,
    Down,
    Up,
    NumlockClear,
    KPDivide,
    KPMultiply,
    KPMinus,
    KPPlus,
    KPEnter,
    KP1,
    KP2,
    KP3,
    KP4,
    KP5,
    KP6,
    KP7,
    KP8,
    KP9,
    KP0,
    KPPeriod,
    Application,
    Power,
    KPEquals,
    F13,
    F14,
    F15,
    F16,
    F17,
    F18,
    F19,
    F20,
    F21,
    F22,
    F23,
    F24,
    Execute,
    Help,
    Menu,
    Select,
    Stop,
    Again,
    Undo,
    Cut,
    Copy,
    Paste,
    Find,
    Mute,
    VolumeUp,
    VolumeDown,
    KPComma,
    KPEqualsAS400,
    Alterase,
    SysReq,
    Cancel,
    Clear,
    Prior,
    Return2,
    Separator,
    Out,
    Oper,
    Clearagain,
    CrSel,
    Exsel,
    KP00,
    KP000,
    ThousandsSeparator,
    DecimalSeparator,
    CurrencyUnit,
    CurrencySubUnit,
    KPLeftParen,
    KPRightParen,
    KPLeftBrace,
    KPRightBrace,
    KPTab,
    KPBackSpace,
    KPA,
    KPB,
    KPC,
    KPD,
    KPE,
    KPF,
    KPXor,
    KPPower,
    KPPercent,
    KPLess,
    KPGreater,
    KPAmpersand,
    KPDblAmpersand,
    KPVerticalBar,
    KPDblVerticalBar,
    KPColon,
    KPHash,
    KPSpace,
    KPAt,
    KPExclam,
    KPMemStore,
    KPMemRecall,
    KPMemClear,
    KPMemAdd,
    KPMemSubstract,
    KPMemMultiply,
    KPMemDivide,
    KPPlusMinus,
    KPClear,
    KPClearEntry,
    KPBinary,
    KPOctal,
    KPDecimal,
    KPHexadecimal,
    LeftControl,
    LeftShift,
    LeftAlt,
    LeftGUI,
    RightControl,
    RightShift,
    RightAlt,
    RGUI,
    Mode,
    AudioNext,
    AudioPrev,
    AudioStop,
    AudioPlay,
    AudioMute,
    MediaSelect,
    WWW,
    Mail,
    Calculator,
    Computer,
    ACSearch,
    ACHome,
    ACBack,
    ACForward,
    ACStop,
    ACRefresh,
    ACBookmarks,
    BrightnessDown,
    BrightnessUp,
    DisplaySwitch,
    KBDIllumToggle,
    KBDIllumDown,
    KBDIllumUp,
    Eject,
    Sleep,
}

VALUES


SDL.keymod

Keyboard modifiers.

Enum

SYNOPSIS

SDL.keymod = {
    None,
    LeftShift,
    RightShift,
    LeftControl,
    RightControl,
    LeftAlt,
    RightAlt,
    LGUI,
    RGUI,
    Num,
    Caps,
    Mode,
}

VALUES


Line

This object is used to pack the lines in most of the rendering functions. It does not map any SDL object.

Table

SYNOPSIS

local l = {
    x1, x2, y1, y2
}

FIELDS

EXAMPLE

local l = {
    x1 = 10,
    y1 = 10,
    x2 = 20,
    y2 = 20
}

Lines

A sequence of line.

Table

SYNOPSIS

local sequence = {
    l1, l2, ..., ln
}

FIELDS

EXAMPLE

local lines = { { x1 = 10, y1 = 10, x2 = 20, y2 = 20 }, { x1 = 100, y1 = 100, x2 = 200, y2 = 200 } }

SDL.logCategory

Enumeration table for logging categories.

Enum

SYNOPSIS

SDL.logCategory = {
    Application,
    Error,
    System,
    Audio,
    Video,
    Render,
    Input,
    Custom
}

VALUES


SDL.logPriority

Enumeration table for logging priorities.

Enum

SYNOPSIS

SDL.logPriority = {
    Verbose,    
    Debug,
    Info,
    Warn,
    Error,
    Critical
}

VALUES


SDL.mouseButton

This enumeration is used to check the state of a single button.

Enum

SYNOPSIS

SDL.mouseButton = {
    Left,
    Right,
    Middle,
    X1,
    X2
}

VALUES


SDL.mouseMask

This enumeration is used to check the state of multiple buttons at the same time.

Function

Enum

SDL.mouseMask = {
    Left,
    Right,
    Middle,
    X1,
    X2
}

VALUES


SDL.pixelFormat

Enum

SYNOPSIS

SDL.pixelFormat = {
    Unknown,
    Index1LSB,
    Index1MSB,
    Index4LSB,
    Index4MSB,
    Index8,
    RGB332,
    RGB444,
    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,
}

VALUES


Point

Point definition.

Table

SYNOPSIS

local p = {
    x, y
}

FIELDS

EXAMPLE

local p = {
    x = 60,
    y = 40,
}

Points

A sequence of Point.

Table

SYNOPSIS

local sequence = {
    p1, p2, ..., pn
}

FIELDS

EXAMPLE

local points = { { x = 10, y = 10 }, { x = 20, y = 40 } }

SDL.powerState

Represents the current power state.

Enum

SYNOPSIS

SDL.powerState = {
    Unknown,  
    OnBattery,
    NoBattery,
    Charging,
    Charged
}

VALUES


SDL.RWCreate

Create a custom RWops object.

Function

SYNOPSIS

rw, err = function SDL.RWCreate(funcs)

ARGUMENTS

RETURNS

Table description

Size

function size()

Returns

The size of the stream

Seek

function seek(offset, whence)

Arguments

Returns

The seek

Read

function read(n, size)

Arguments

Returns

  1. The string read
  2. The number of bytes read

Write

function write(data, n, size)

Arguments

Returns

  1. The number of bytes written

Close

function close()

EXAMPLE

local SDL       = require "SDL" 

-- The table for RW ops
local reader    = { }

function reader.size()
        return -1
end

function reader.read(n, size)
        local r = reader.file:read(n * size)    

        if not r then
                return nil, 0
        end

        return r, #r
end

function reader.write(data, n, size)
        local r = reader.file:write(data)

        if not r then
                return 0
        end

        return n * size
end

function reader.seek(offset, whence)
        local v = nil

        if whence == SDL.rwopsSeek.Set then
                v = "set" 
        elseif whence == SDL.rwopsSeek.Current then
                v = "cur" 
        elseif whence == SDL.rwopsSeek.End then
                v = "end" 
        end

        if not v then
                error("unknown whence")
        end

        local r = reader.file:seek(v, offset)

        if not r then
                return 0
        end

        return r
end

function reader.close()
        reader.file:close()
end

reader.file = io.open("mario.png", "r")
if not reader.file then
        -- Handle your error here
        error("Failed to load")
end

local rw = SDL.RWCreate(reader)

SDL.RWFromFile

Create a RWops object from a file.

Function

SYNOPSIS

function SDL.RWFromFile(path, mode)

ARGUMENTS

RETURNS

  1. the RWops object or nil
  2. the error message

RWops

The underlying object for SDL_RWops.

Methods

Method Description
RW:close Close the RW
RW:read Read some data
RW:readByte Read a byte
RW:seek Move in the RW
RW:tell Tell where we are
RW:write Write some data
RW:writeByte Write a byte

RW:close

Close the stream.

Method

SYNOPSIS

function RW:close()

RETURNS

  1. true on success or false
  2. the error message

SDL.rwopsSeek

Whence for RWops.

Enum

SYNOPSIS

SDL.rwopsSeek = {
    Set,
    Current,
    End
}

VALUES


SDL.rwopsType

The type of RWops.

Enum

SYNOPSIS

SDL.rwopsType = {
    Unknown,
    WinFile,
    StdFile,
    JNIFile,
    Memory,
    MemoryRO
}

VALUES


Rect

Table equivalent for SDL_Rect.

Table

SYNOPSIS

local r = {
    w, h, x, y
}

FIELDS

EXAMPLE

local r = { 10, 10, -10, -5 }

Rects

A sequence of Rect.

Table

SYNOPSIS

local sequence = {
    r1, r2, ..., rn
}

FIELDS

EXAMPLE

local s = { { 5, 5, 10, 10 }, { 10, 10, 20, 20 } }

Renderer:clear

Clear the renderer.

Method

SYNOPSIS

ret, err = function Renderer:clear()

RETURNS


Renderer:copy

Copy a texture to the renderer.

Method

SYNOPSIS

ret, err = function Renderer:copy(texture, srcrect, dstrect)

ARGUMENTS

RETURNS


Renderer:copyEx

Copy texture to the renderer. The table may or must have the following fields:

Method

SYNOPSIS

ret, err = function Renderer:copyEx(params)

ARGUMENTS

RETURNS


Renderer:createTexture

Create a texture.

Method

SYNOPSIS

tex, err = function Renderer:createTexture(format, access, width, height)

ARGUMENTS

RETURNS


Renderer:createTextureFromSurface

Create a texture from a surface.

Method

SYNOPSIS

tex, err = function Renderer:createTextureFromSurface(surface)

ARGUMENTS

RETURNS


Renderer:drawLine

Draw a line with the current set color.

Method

SYNOPSIS

ret, err = function Renderer:drawLine(line)

ARGUMENTS

RETURNS


Renderer:drawLines

Draw a series of connected lines.

Method

SYNOPSIS

ret, err = function Renderer:drawLines(points)

ARGUMENTS

RETURNS


Renderer:drawPoint

Draw a point with the current color.

Method

SYNOPSIS

ret, err = function Renderer:drawPoint(point)

ARGUMENTS

RETURNS


Renderer:drawPoints

Draw several points.

Method

SYNOPSIS

ret, err = function Renderer:drawPoints(points)

ARGUMENTS

RETURNS


Renderer:drawRect

Draw a rectangle.

Method

SYNOPSIS

ret, err = function Renderer:drawRect(rect)

ARGUMENTS

RETURNS


Renderer:drawRects

Draw rectangles.

Method

SYNOPSIS

ret, err = function Renderer:drawRects(rects)

ARGUMENTS

RETURNS


Renderer:fillRect

Fill a rectangle.

Method

SYNOPSIS

ret, err = function Renderer:fillRect(rect)

ARGUMENTS

RETURNS


Renderer:fillRects

Fill rectangles.

Method

SYNOPSIS

ret, err = function Renderer:fillRects(rects)

ARGUMENTS

RETURNS


SDL.rendererFlags

The renderer flags.

Enum

SYNOPSIS

SDL.rendererFlags = {
    Software,
    Accelerated,
    PresentVSYNC,
    TargetTexture
}

VALUES


SDL.rendererFlip

Renderer flip.

Enum

SYNOPSIS

SDL.rendererFlip = {
    None,
    Horizontal,
    Vertical
}

VALUES


Renderer:getClipRect

Get the clipping rectangle.

Method

SYNOPSIS

rect = function Renderer:getClipRect()

RETURNS


Renderer:getDrawBlendMode

Get the drawing blend mode.

Method

SYNOPSIS

mode = function Renderer:getDrawBlendMode()

RETURNS


Renderer:getDrawColor

Get the drawing color.

Method

SYNOPSIS

hex, c, err = function Renderer:getDrawColor()

RETURNS


Renderer:getInfo

Get the renderer information.

Method

SYNOPSIS

info, err = function Renderer:getInfo()

RETURNS


Renderer:getViewport

Get the view port.

Method

SYNOPSIS

rect = function Renderer:getViewport()

RETURNS


Renderer:getLogicalSize

Get device independent resolution for rendering.

Method

SYNOPSIS

w, h = function Renderer:getLogicalSize()

RETURNS


RendererInfo

The renderer information.

Table

SYNOPSIS

local info = {
    name,
    flags,
    numTextureFormats,
    maxTextureWidth,
    maxTextureHeight,
    textureFormats
}

FIELDS


Renderer

The renderer object.

Object

Methods

Method Description
Renderer:createTexture Create a texture
Renderer:createTextureFromSurface Create a texture
Renderer:clear Clear the renderer
Renderer:copy Copy to the renderer
Renderer:copyEx Copy to the renderer
Renderer:drawLine Draw a line
Renderer:drawLines Draw lines
Renderer:drawPoint Draw a point
Renderer:drawPoints Draw points
Renderer:drawRect Draw a rectangle
Renderer:drawRects Draw rectangles
Renderer:fillRect Fill rectangle
Renderer:fillRects Fill rectangles
Renderer:getClipRect Get the clipping rectangle
Renderer:getDrawBlendMode Get the drawing blend mode
Renderer:getDrawColor Get the drawing color
Renderer:getRendererInfo Get the info
Renderer:getViewport Get the viewport
Renderer:getLogicalSize Get device independent resolution for rendering
Renderer:present Present the renderer
Renderer:setClipRect Set the clipping rectangle
Renderer:setDrawBlendMode Set the drawing blend mode
Renderer:setDrawColor Set the drawing color
Renderer:setTarget Set the target
Renderer:setViewport Set the viewport
Renderer:setLogicalSize Set a device independent resolution for rendering

Renderer:present

Present the renderer.

Method

SYNOPSIS

function Renderer:present()

Renderer:setClipRect

Set the clipping rectangle.

Method

SYNOPSIS

ret, err = function Renderer:setClipRect(rect)

ARGUMENTS

RETURNS


Renderer:setDrawBlendMode

Set the draw blend mode.

Method

SYNOPSIS

ret, err = function Renderer:setDrawBlendMode(mode)

ARGUMENTS

RETURNS


Renderer:setDrawColor

Set the drawing color.

Method

SYNOPSIS

ret, err = function Renderer:setDrawColor(c)

ARGUMENTS

RETURNS


Renderer:setTarget

Set the target texture.

Method

SYNOPSIS

ret, err = function Renderer:setTarget(texture)

ARGUMENTS

RETURNS


Renderer:setViewport

Set the view port.

Method

SYNOPSIS

ret, err = function Renderer:setViewport(rect)

ARGUMENTS

RETURNS


Renderer:setLogicalSize

Set a device independent resolution for rendering.

Method

SYNOPSIS

ret, err = function Renderer:setLogicalSize(w, h)

ARGUMENTS

RETURNS


SDL.scancode

Scancodes.

Enum

SYNOPSIS

SDL.scancode = {
    Unknown,
    A,
    B,
    C,
    D,
    E,
    F,
    G,
    H,
    I,
    J,
    K,
    L,
    M,
    N,
    O,
    P,
    Q,
    R,
    S,
    T,
    U,
    V,
    W,
    X,
    Y,
    Z,
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
    0,
    Return,
    Escape,
    Backspace,
    Tab,
    Space,
    Minus,
    Equals,
    LeftBracket,
    RightBracked,
    Backslash,
    NonUShash,
    SemiColon,
    Apostrophe,
    Grave,
    Comma,
    Period,
    Slash,
    CapsLock,
    F1,
    F2,
    F3,
    F4,
    F5,
    F6,
    F7,
    F8,
    F9,
    F10,
    F11,
    F12,
    PrintScreen,
    ScrollLock,
    Pause,
    Insert,
    Home,
    PageUp,
    Delete,
    End,
    PageDown,
    Right,
    Left,
    Down,
    Up,
    NumlockClear,
    KPDivide,
    KPMultiply,
    KPMinus,
    KPPlus,
    KPEnter,
    KP1,
    KP2,
    KP3,
    KP4,
    KP5,
    KP6,
    KP7,
    KP8,
    KP9,
    KP0,
    KPPeriod,
    NonUSBackslash,
    Application,
    Power,
    KPEquals,
    F13,
    F14,
    F15,
    F16,
    F17,
    F18,
    F19,
    F20,
    F21,
    F22,
    F23,
    F24,
    Execute,
    Help,
    Menu,
    Select,
    Stop,
    Again,
    Undo,
    Cut,
    Copy,
    Paste,
    Find,
    Mute,
    VolumeUp,
    VolumeDown,
    Comma,
    KPEqualsAS400,
    International1,
    International2,
    International3,
    International4,
    International5,
    International6,
    International7,
    International8,
    International9,
    Lang1,
    Lang2,
    Lang3,
    Lang4,
    Lang5,
    Lang6,
    Lang7,
    Lang8,
    Lang9,
    Alterase,
    Sysreq,
    Cancel,
    Clear,
    Prior,
    Return2,
    Separator,
    Out,
    Oper,
    Clearagain,
    CrSel,
    Exsel,
    KP00,
    KP000,
    ThousandsSeparator,
    DecimalSeparator,
    CurrencyUnit,
    CurrencySubUnit,
    LeftParen,
    RightParen,
    LeftBrace,
    RightBrace,
    KPTab,
    KPBackspace,
    KPA,
    KPB,
    KPC,
    KPD,
    KPE,
    KPF,
    KPXor,
    KPPower,
    KPPercent,
    KPLess,
    KPGreater,
    KPAmpersand,
    KPDblAmpersand,
    KPVerticalBar,
    KPDblVerticalBar,
    KPColon,
    KPHash,
    KPSpace,
    KPAt,
    KPExclam,
    KPMemStore,
    KPMemRecall,
    KPMemClear,
    KPMemAdd,
    KPMemSubstract,
    KPMemMultiply,
    KPMemDivide,
    KPPlusMinus,
    KPClear,
    KPClearEntry,
    KPBinary,
    KPOctal,
    KPDecimal,
    KPHexadecimal,
    LeftControl,
    LeftShift,
    LeftAlt,
    LeftGUI,
    RightControl,
    RightShift,
    RightAlt,
    RGUI,
    Mode,
    AudioNext,
    AudioPrev,
    AudioStop,
    AudioPlay,
    AudioMute,
    MediaSelect,
    WWW,
    Mail,
    Calculator,
    Computer,
    ACSearch,
    ACHome,
    ACBack,
    ACForward,
    ACStop,
    ACRefresh,
    ACBookmarks,
    BrightnessDown,
    BrightnessUp,
    DisplaySwitch,
    KBDIllumToggle,
    KBDIllumDown,
    KBDIllumUp,
    Eject,
    Sleep,
    App1,
    App2,
}

VALUES


Surface:blit

Blit a surface.

Method

SYNOPSIS

ret, rect, err = function Surface:blit(surface, srcrect, dstrect)

ARGUMENTS

RETURNS


Surface:blitScaled

Blit a surface.

Method

SYNOPSIS

ret, rect, err = function Surface:blitScaled(surface, srcrect, dstrect)

ARGUMENTS

RETURNS


Surface:convertFormat

Convert this surface with a format and return the converted one. This surface stays valid after the conversion

Method

SYNOPSIS

s, err = function Surface:convertFormat(format)

ARGUMENTS

RETURNS


Surface:fillRect

Fill the surface with a color.

Method

SYNOPSIS

ret, err = function Surface:fillRect(rect, color)

ARGUMENTS

RETURNS


Surface:fillRects

Fill the surface with a color.

Method

SYNOPSIS

ret, err = function Surface:fillsRects(rects, color)

ARGUMENTS

RETURNS


Surface:getAlphaMod

Get the alpha mod.

Method

SYNOPSIS

mod, err = function Surface:getAlphaMod()

RETURNS


Surface:getBlendMode

Get the blend mode.

Method

SYNOPSIS

mod, err = function Surface:getBlendMode()

RETURNS


Surface:getClipRect

Get the clipping rectangle.

Method

SYNOPSIS

rect = function Surface:getClipRect()

RETURNS


Surface:getColorKey

Get the surface color key.

Method

SYNOPSIS

hex, c, err = function Surface:getColorKey()

RETURNS


Surface:getColorMod

Get the color mod.

Method

SYNOPSIS

hex, c, err = function Surface:getColorMod()

RETURNS


Surface:lock

Lock the surface.

Method

SYNOPSIS

ret, err = function Surface:lock()

RETURNS


Surface:lowerBlit

Blit a surface.

Method

SYNOPSIS

ret, rect, err = function Surface:lowerBlit(surface, srcrect, dstrect)

ARGUMENTS

RETURNS


Surface:lowerBlitScaled

Blit a surface.

Method

SYNOPSIS

ret, rect, err = function Surface:lowerBlitScaled(surface, srcrect, dstrect)

ARGUMENTS

RETURNS


Surface:mustLock

Tells if we must lock the surface.

Method

SYNOPSIS

ret = function Surface:mustLock()

RETURNS


Surface

The object for SDL_Surface.

Object

Methods

Method Description
Surface:blit Blit surfaces
Surface:blitScaled Blit surfaces in scaled mode
Surface:convertFormat Convert to a specific format
Surface:fillRect Fill the surface
Surface:fillRects Fill the surface
Surface:getClipRect Get the clip rectangle
Surface:getColorKey Get the color key
Surface:getAlphaMod Get the surface alpha mod
Surface:getBlendMode Get the surface blend mod
Surface:getColorMod Get the surface color mod
Surface:lock Lock the surface
Surface:lowerBlit Blit surfaces
Surface:lowerBlitScaled Blit surfaces in scaled mode
Surface:mustLock Tell if we must lock
Surface:saveBMP Save the surface to BMP file
Surface:saveBMP_RW Save the surface to BMP file
Surface:setClipRect Set the clip rectangle
Surface:setColorKey Set the color key
Surface:setAlphaMod Set the alpha mod
Surface:setBlendMode Set the blend mod
Surface:setColorMod Set the color mod
Surface:setPalette Set the palette
Surface:setRLE Set RLE
Surface:unlock Unlock a surface

Surface:saveBMP

Save the surface as a BMP to a file.

Method

SYNOPSIS

ret, err = function Surface:saveBMP(path)

ARGUMENTS

RETURNS


Surface:saveBMP_RW

Save the surface as BMP to a RWops.

Method

SYNOPSIS

ret, err = function Surface:saveBMP_RW(rwops)

ARGUMENTS

RETURNS


Surface:setAlphaMod

Set the alpha mod.

Method

SYNOPSIS

ret, err = function Surface:setAlphaMod(mod)

ARGUMENTS

RETURNS


Surface:setBlendMode

Set the blend mode.

Method

SYNOPSIS

ret, err = function Surface:setBlendMode(mod)

ARGUMENTS

RETURNS


Surface:setClipRect

Set the clipping rectangle.

Method

SYNOPSIS

ret = function Surface:setClipRect(rect)

ARGUMENTS

RETURNS


Surface:setColorKey

Set the surface color key.

Method

SYNOPSIS

ret, err = function Surface:setColorKey(color)

ARGUMENTS

RETURNS


Surface:setColorMod

Set the color mod.

Method

SYNOPSIS

ret, err = function Surface:setColorMod(color)

ARGUMENTS

RETURNS


Surface:setPalette

Set the palette for the surface.

Method

SYNOPSIS

ret, err = function Surface:setPalette(colors)

ARGUMENTS

RETURNS


Surface:setRLE

Set the RLE acceleration.

Method

SYNOPSIS

ret, err = function Surface:setRLE(mode)

ARGUMENTS

RETURNS


Surface:unlock

Unlock the surface.

Method

SYNOPSIS

function Surface:unlock()

SDL.textureAccess

The texture access.

Enum

SYNOPSIS

SDL.textureAccess = {
    Static,
    Streaming,
    Target
}

VALUES


Texture:getAlphaMod

Get the the alpha mod.

Method

SYNOPSIS

mod = function Texture:getAlphaMod()

RETURNS


Texture:getBlendMode

Get the blend mod.

Method

SYNOPSIS

mod = function Texture:getBlendMode()

RETURNS


Texture:getColorMod

Get the color mod.

Method

SYNOPSIS

hex, c = function Texture:getColorMod()

RETURNS


SDL.textureModulate

The texture modulate.

Enum

SYNOPSIS

SDL.textureModulate = {
    None,
    Color,
    Alpha
}

VALUES


Texture

The SDL_Texture wrapper.

Object

Methods

Method Description
Texture:getAlphaMod Get the alpha mod
Texture:getBlendMode Get the blend mod
Texture:getColorMod Get the color mod
Texture:lock Lock the texture
Teture:query Query the texture
Texture:setAlphaMod Set the alpha mod
Texture:setBlendMode Set the blend mod
Texture:setColorMod Set the color mod
Texture:unlock Unlock the texture
Texture:update Update the texture content

Texture:query

Query the texture.

Method

SYNOPSIS

format, access, width, height = function Texture:query()

RETURNS


Texture:setAlphaMod

Set the alpha mod.

Method

SYNOPSIS

ret, err = function Texture:setAlphaMod(value)

ARGUMENTS

RETURNS


Texture:setBlendMode

Set the blend mod.

Method

SYNOPSIS

ret, err = function Texture:setBlendMode(value)

ARGUMENTS

RETURNS


Texture:setColorMod

Set the color mod.

Method

SYNOPSIS

ret, err = function Texture:setColorMod(color)

ARGUMENTS

RETURNS


Texture:unlock

Unlock the texture.

Method

SYNOPSIS

function Texture:unlock()

Thread:getId

Get the thread id.

Method

SYNOPSIS

id = function Thread:getId()

RETURNS


Thread:getName

Get the thread name.

Method

SYNOPSIS

name = function Thread:getName()

RETURNS


Thread

The thread object.

Methods

Method Description
Thread:wait Wait a thread to finish
Thread:getId Get the thread id
Thread:getName Get the thread name

Thread:wait

Wait a thread to finish its execution.

Method

SYNOPSIS

ret = function Thread:wait()

RETURNS


TimerCallback

This callback is used by the function SDL.addTimer. It can be a path to a file or a function. The function takes the interval and must return the next time interval.

Function

SYNOPSIS

interval = function callback(interval)

ARGUMENTS

RETURNS


Timer:id

Get the timer id.

Method

SYNOPSIS

id = function Timer:id()

RETURNS


Timer

The timer object.

Methods

Method Description
Timer:remove Remove the timer
Timer:id Get the timer id

Timer:remove

Remove the timer.

Method

SYNOPSIS

ret = function Timer:remove()

RETURNS


WAV

This object is a WAV file description usually loaded from SDL.loadWAV.

Table

SYNOPSIS

local w = {
    data,
    length,
    format,
    frequency,
    channels,
    samples
}

FIELDS


SDL.window

An enumeration of window states.

Enum

SYNOPSIS

SDL.window = {
    Fullscreen,
    Desktop,
    OpenGL,
    Shown,
    Hidden,
    Borderless,
    Resizable,
    Minimized,
    Maximized,
    InputGrabbed,
    InputFocused,
    MouseFocused,
    Foreign
}

VALUES


Window:getBrightness

Use this function to get the brightness (gamma correction) for a window.

Method

SYNOPSIS

brightness = function Window:getBrightness()

RETURNS


Window:getDisplayIndex

Use this function to get the index of the display associated with a window.

Method

SYNOPSIS

index = function Window:getDisplayIndex()

RETURNS


Window:getDisplayMode

Use this function to fill in information about the display mode to use when a window is visible at fullscreen.

Method

SYNOPSIS

mode = function Window:getDisplayMode()

RETURNS


Window:getFlags

Use this function to get the window flags.

Method

SYNOPSIS

flags = function Window:getFlags()

RETURNS

EXAMPLE

--
-- win is a previously created window
--
local flags = win:getFlags()

if flags[SDL.window.Fullscreen] then
    print("Running in fullscreen")
end

Window:getGammaRamp

Use this function to get the gamma ramp for a window.

Method

SYNOPSIS

gamma = function Window:getGammaRamp()

RETURNS

EXAMPLES

local gamma = win:getGammaRamp()

print("Red")
for i = 1, 256 do
    print(string.format("%d", gamma[1][i]))
end

print("Green")
for i = 1, 256 do
    print(string.format("%d", gamma[2][i]))
end

print("Blue")
for i = 1, 256 do
    print(string.format("%d", gamma[3][i]))
end

Window:getGrab

Use this function to get a window's input grab mode.

Method

SYNOPSIS

grab = function Window:getGrab()

RETURNS


Window:getID

Use this function to get the numeric ID of a window, for logging purposes.

Method

SYNOPSIS

id = function Window:getID()

RETURNS


Window:getMaximumSize

Use this function to get the maximum size of a window's client area.

Method

SYNOPSIS

width, height = function Window:getMaximumSize()

RETURNS


Window:getMinimumSize

Use this function to get the minimum size of a window's client area.

Method

SYNOPSIS

width, height = function Window:getMinimumSize()

RETURNS


Window:getPixelFormat

Method

SYNOPSIS

format = function Window:getPixelFormat()

RETURNS


Window:getPosition

Use this function to get the position of a window.

Method

SYNOPSIS

x, y = function Window:getPosition()

RETURNS


Window:getSize

Use this function to get the size of a window's client area.

Method

SYNOPSIS

width, height = function Window:getSize()

RETURNS


Window:getSurface

Get the window surface. The surface will not be garbage collected.

Method

SYNOPSIS

surface, err = function Window:getSurface()

RETURNS


Window:getTitle

Use this function to get the title of a window.

Method

SYNOPSIS

title = function Window:getTitle()

RETURNS


Window:hide

Use this function to hide a window.

Method

SYNOPSIS

function Window:hide()

Window:maximize

Use this function to make a window as large as possible.

Method

SYNOPSIS

function Window:maximize()

Window:minimize

Use this function to minimize a window to an iconic representation.

Method

SYNOPSIS

function Window:minimize()

Window

A window is the object oriented representation of the SDL_Window structure. It is automatically destroyed when the Lua garbage collector collect it.

Object

Methods

Method Description
Window:getBrightness Get the brightness
Window:getDisplayIndex Get the display index
Window:getDisplayMode Get the display mode
Window:getFlags Get the window flags
Window:getGammaRamp Get the gamma ramp
Window:getGrab Get the grab mode
Window:getID Get the window id
Window:getMaximumSize Get the maximum size
Window:getMinimumSize Get the minimum size
Window:getPixelFormat Get the window pixel format
Window:getPosition Get the window position
Window:getSurface Get the window surface
Window:getSize Get the current size
Window:getTitle Get the window title
Window:hide Hide the window
Window:maximize Maximize the window
Window:minimize Minimize the window
Window:raise Raise the window
Window:restore Restore the window
Window:setBrightness Set the brightness
Window:setDisplayMode Set the display mode
Window:setFullscreen Set the fullscreen mode
Window:setGammaRamp Set the gamma ramp
Window:setGrab Set the grab mode
Window:setIcon Set the surface icon
Window:setMaximumSize Set the maximum size
Window:setMinimumSize Set the minimum size
Window:setPosition Set the window position
Window:setSize Set the current size
Window:setTitle Set the window title
Window:show Show the window
Window:updateSurface Update the surface
Window:updateSurfaceRects Update the surface by rectangles
Window:warpMouse Warp the mouse

Window:raise

Use this function to raise a window above other windows and set the input focus.

Method

SYNOPSIS

function Window:raise()

Window:restore

Use this function to restore the size and position of a minimized or maximized window.

Method

SYNOPSIS

function Window:restore()

Window:setBrightness

Use this function to set the brightness (gamma correction) for a window.

Method

SYNOPSIS

function Window:setBrightness(brightness)

ARGUMENTS


Window:setDisplayMode

Use this function to set the display mode to use when a window is visible at fullscreen.

Method

SYNOPSIS

ret, err = function Window:setDisplayMode(mode)

ARGUMENTS

RETURNS


Window:setFullscreen

Use this function to set a window's fullscreen state.

Method

SYNOPSIS

ret, err = function Window:setFullscreen(flags)

ARGUMENTS

RETURNS

EXAMPLES

--
-- win was previously created
--
win:setFullscreen(SDL.window.Fullscreen)

Window:setGammaRamp

Use this function to set the gamma ramp for a window.

Method

SYNOPSIS

ret, err = function Window:setGammaRamp(gamma)

ARGUMENTS

RETURNS

EXAMPLES

local red    = { }
local green  = { }
local blue   = { }

--
-- Fill red, green and blue arrays from 1 to 256 with your values
--

win:setGammaRamp(red, green, blue)

Window:setGrab

Use this function to set a window's input grab mode.

Method

SYNOPSIS

function Window:setGrab(mode)

ARGUMENTS


Window:setIcon

Set the window icon with a surface.

Method

SYNOPSIS

function Window:setIcon(surface)

ARGUMENTS


Window:setMaximumSize

Use this function to set the maximum size of a window's client area.

Method

SYNOPSIS

function Window:setMaximumSize(w, h)

ARGUMENTS


Window:setMinimumSize

Use this function to set the minimum size of a window's client area.

Method

SYNOPSIS

function Window:setMinimumSize(w, h)

ARGUMENTS


Window:setPosition

Use this function to set the position of a window.

Method

SYNOPSIS

function Window:setPosition(x, y)

ARGUMENTS


Window:setSize

Use this function to set the size of a window's client area.

Method

SYNOPSIS

function Window:setSize(w, h)

ARGUMENTS


Window:setTitle

Use this function to set the title of a window.

Method

SYNOPSIS

function Window:setTitle(title)

ARGUMENTS


Window:show

Use this function to show a window.

Function

SYNOPSIS

function Window:show()

Window:updateSurface

Use this function to copy the window surface to the screen.

Method

SYNOPSIS

ret, err = function Window:updateSurface()

RETURNS


Window:warpMouse

Use this function to move the mouse to the given position within the window.

Method

SYNOPSIS

function Window:warpMouse(x, y)

ARGUMENTS


SDL.addEventWatch

Add an event watcher.

Function

SYNOPSIS

filter = function SDL.addEventWatch(fn)

ARGUMENTS

RETURNS

REMARKS

The function must have the following signature:

function (event)

Where arguments are:


SDL.addTimer

Add timer which will be at a specific interval.

You can pass optional parameters to the thread source except userdata and functions.

Function

SYNOPSIS

timer, err = function SDL.addTimer(interval, path)

ARGUMENTS

RETURNS

EXAMPLES

local t = SDL.addTimer(1000, "check.lua")

Function

SYNOPSIS

function SDL.addTimer(interval, func)

ARGUMENTS

RETURNS

EXAMPLES

local function job(interval)
    while true do
        print("...")
    end

    return interval
end

local t = SDL.addTimer(1000, job)

SDL.audioInit

Initialize the audio system.

Function

SYNOPSIS

ret, err = function SDL.audioInit(name)

ARGUMENTS

RETURNS


SDL.audioQuit

Close the audio.

Function

SYNOPSIS

function SDL.audioQuit()

Audio

The audio API is designed a bit differently than SDL's one. The audio callback runs in a separate thread which makes hard to share data between the audio callback and the host program.

This API is very complex and you may prefer using SDL_mixer instead.

Objects

Object Description
AudioDevice The audio device

Types

Type Description
AudioCallback The audio callback
WAV A wav file description

Tables

Table Description
SDL.audioFormat The audio format
SDL.audioStatus The audio status

Functions

Function Description
SDL.audioInit Initialize the audio system
SDL.audioQuit Close the audio system
SDL.convertAudio Convert audio data
SDL.getAudioDeviceName Get an audio device name
SDL.getAudioDriver Get a SDL audio driver name
SDL.getAudioStatus Get the audio status
SDL.getCurrentAudioDriver get the current audio driver name
SDL.getNumAudioDevices Get the number of audio devices
SDL.getNumAudioDrivers Get the number of audio drivers
SDL.loadWAV Load a WAV file
SDL.loadWAV_RW Load a wav file from a RWops
SDL.mixAudio Mix some audio
SDL.mixAudioFormat Mix some audio with a format
SDL.openAudio Open the audio
SDL.openAudioDevice open an audio device

Channels

The channel API is a Lua-SDL2 specific API, it does not exist in SDL. It has been designed to allow user to pass data between threads.

The following types may be passed from channels functions:

Objects

Object Description
Channel The channel object

Functions

Function Description
SDL.getChannel Get or create a channel object

Color

Within Lua-SDL there are two ways to pass a color to a function. it is allowed to pass the hexadecimal version or a table with the fields r, g, b.

Types

Type Description
Color (table) Color definition as a table
Color (hexadecimal) Color definition as an hexadecimal number
Colors A sequence of colors

Display

General display inspection and management.

Tables

Table Description
SDL.pixelFormat The pixel format

Functions

Function Description
SDL.disableScreenSaver Disable the screen saver
SDL.enableScreenSaver Enable the screen saver
SDL.getClosestDisplayMode Get the closest display mode
SDL.getCurrentDisplayMode Get the current display mode
SDL.getCurrentVideoDriver Get the current video driver
SDL.getDesktopDisplayMode Get the desktop display mode
SDL.getDisplayBounds Get the display bounds
SDL.getDisplayMode Get display mode
SDL.getNumDisplayModes Get the number of display modes
SDL.getNumVideoDisplays Get the number of video displays
SDL.getNumVideoDrivers Get the number of video drivers
SDL.getVideoDriver Get the video driver
SDL.isScreenSaverLoaded Check if the screen saver is loaded
SDL.videoInit Init the video
SDL.videoQuit Quit the video

Error

Usually errors are always reported by all exported functions. However if needed user can get or set SDL errors on its own.

Functions

Function Description
SDL.clearError Clear the current error
SDL.setError Set an error
SDL.getError Get the current SDL error

Event handling

Objects

Object Description
Filter The filter object

Types

Type Description
Event The event table

Tables

Table Description
SDL.event The type of event
SDL.eventAction Action to execute for filtering
SDL.eventWindow Window event

Functions

Function Description
SDL.addEventWatch Add a function to watch new events
SDL.eventState Enable or disable events by types
SDL.filterEvents Filter events from the queue
SDL.flushEvent Flush events by type
SDL.flushEvents Flush events by range
SDL.hasEvent Check for events by type
SDL.hasEvents Check for events by range
SDL.peepEvents Check and optionally get events from the queue
SDL.pollEvent Read pending events
SDL.pumpEvents Add all input events to the queue
SDL.quitRequested Check if the quit event is queued
SDL.registerEvents Register new events
SDL.setEventFilter Filter events before they are pushed to the queue
SDL.waitEvent Wait for event with optional timeout

Filesystem

Functions from filesystem category.

Available since 2.0.3-2

Functions

Function Description Version
SDL.getBasePath Base application path +2.0.3-2
SDL.getPrefPath The preference path +2.0.3-2

OpenGL rendering

This sections bind the specific SDL GL functions for Lua-SDL2.

Object

Object Description
Context Opaque GL context

Tables

Table Description
SDL.glAttr GL attributes
SDL.glProfile GL profile
SDL.glFlags GL context flags

Functions

Function Description
SDL.glExtensionSupported Check if an extension is supported
SDL.glSetAttribute Set an attribute
SDL.glGetAttribute Get an attribute
SDL.glCreateContext Create a context
SDL.glMakeCurrent Make a context current
SDL.glGetCurrentWindow Get the current window
SDL.glGetCurrentContext Get the current context
SDL.glGetDrawableSize Get the drawable size
SDL.glSetSwapInterval Set the swap interval
SDL.glGetSwapInterval Get the swap interval
SDL.glSwapWindow Update the window
SDL.glDeleteContext Delete a context

Haptic

Force feedback support.

Objects

Object Description
Haptic The haptic object

Types

Type Description
HapticEffect The haptic effect description
HapticDirectionType The haptic direction table

Tables

Table Description
SDL.hapticType The type of force feedback
SDL.hapticDirection The direction

Functions

Function Description
SDL.hapticOpen Open an haptic
SDL.hapticOpenFromJoystick Open from a joystick
SDL.hapticOpenFromMouse Open from the mouse
SDL.hapticOpened Check if opened
SDL.mouseIsHaptic Check if mouse is haptic
SDL.joystickIsHaptic Check if a joystick is haptic
SDL.numHaptics Get number of haptic

Hints

This category contains functions to set and get configuration hints, as well as listing each of them alphabetically.

Tables

Table Description
SDL.hintPriority Hints priorities
SDL.hint Available hints

Functions

Function Description
SDL.clearHints Clear hints
SDl.getHint Get a hint
SDl.setHint Set a hint

Initialization

Constants

Variable Description
VERSION_MAJOR The major SDL version
VERSION_MINOR The minor SDL version
VERSION_PATCH The patch SDL version
VERSION_BINDING The Lua-SDL2 binding version

Tables

Table Description
SDL.flags Initialization flags

Functions

Function Description
SDL.init Initialize SDL
SDL.initSubSystem Initialize a SDL subsystem
SDL.quit Quit SDL
SDL.quitSubSystem Quit a SDL subsystem
SDL.wasInit Check what was init

Joystick

This category provides support for joystick management.

Objects

Object Description
Joystick The joystick object

Tables

Table Description
SDL.joyHat The hat enumeration

Functions

Function Description
SDL.joystickOpen Open a joystick
SDL.joystickEventState Set the joystick state
SDL.numJoysticks Get the number of joysticks available
SDL.joystickNameForIndex Get a joystick name by index
SDL.joystickUpdate Update joystick

Keyboard

Keyboard management and enumerations.

Tables

Table Description
SDL.key List of keys
SDL.scancode List of scancodes
SDL.keymod List of key modifiers

Functions

Function Description
SDL.getKeyFromName Get a key from name
SDL.getKeyFromScancode Get a key from a scancode
SDL.getKeyName Get key name
SDL.getKeyboardFocus Get the window by keyboard focus
SDL.getKeyboardState Get the keyboard state
SDL.getModState Get the mod state
SDL.getScancodeFromKey Get scancode from key
SDL.getScancodeFromName Get scancode from name
SDL.getScancodeName Get scancode name
SDL.setModState Set the mod state
SDL.setTextInputRect Set the input text rectangle
SDL.startTextInput Start text input
SDL.stopTextInput Stop text input

Line

Line management is done with Lua tables.

Types

Type Description
Line A line definition
Lines A sequence of lines

Logging

This category contains functions for handling simple log messages with categories and priorities.

Tables

Table Description
SDL.logCategory The category
SDL.logPriority The priority

Functions

Function Description
SDL.log Log a message
SDL.logCritical Log a critical message
SDL.logDebug Log a debug message
SDL.logError Log an error message
SDL.logInfo Log an information message
SDL.logVerbose Log a verbose message
SDL.logWarn Log a warning
SDL.logMessage Log a specific message
SDL.logGetOutputFunction Get the output function
SDL.logGetPriority Get the priority
SDL.logResetPriorities Reset all priorities
SDL.logSetAllPriority Set all priorities
SDL.logSetOutputFunction Set a logging function

Mouse

This category contains functions for handling inputs from mice and other similar pointing devices, as well as some cursor management tasks.

Tables

Table Description
SDL.mouseButton Single button enumeration
SDL.mouseMask Mask for multiple buttons

Functions

Function Description
SDL.createColorCursor Create a color cursor
SDL.createCursor Create a cursor
SDL.getCursor Get the active cursor
SDL.getMouseFocus Get the window focused by mouse
SDL.getMouseState Get the current state
SDL.getRelativeMouseMode Get the relative mouse mode
SDL.getRelativeMouseState Get the relative mouse state
SDL.setCursor Set the mouse cursor
SDL.setRelativeMouseMode Set the relative mouse mode
SDL.showCursor Show the cursor

Platform

This category contains functions for handling information about the current platform.

Functions

Function Description
SDL.getPlatform Get the platform

Point

A point represent a two dimensional coordinates. It is mapped as a table.

Types

Type Description
Point A point
Points A sequence of points

Power management

This category contains functions for handling SDL power management routines.

Tables

Table Description
SDL.powerState The power state

Functions

Function Description
SDL.getPowerInfo Get the power information

Rectangle

Withing Lua-SDL, rectangles (aka SDL_Rect) are managed with simple Lua tables.

Types

Type Description
Rect A rectangle
Rects A sequence of rectangles

Renderer

Accelerated rendering.

Objects

Object Description
Renderer The renderer object

Types

Type Description
RendererInfo The renderer information

Tables

Table Description
SDL.rendererFlags Renderer flags
SDL.rendererFlip Renderer flip

Functions

Function Description
SDL.createRenderer Create a renderer
SDL.createSoftwareRenderer Create a software renderer
SDL.getNumRenderDrivers Get the number of rendering drivers
SDL.getRenderDriverInfo Get the renderer driver information

RWops

Objects

Object Description
RWops File system operations

Tables

Table Description
SDL.rwopsSeek Whence
SDL.rwopsType Type of RWops

Functions

Function Description
SDL.RWCreate Create a custom RW
SDL.RWFromFile Create RW from a file

Surface management

Objects

Object Description
Surface The SDL_Surface wrapper

Tables

Table Description
SDL.blendMode The blend mode enumeration

Functions

Function Description
SDL.createRGBSurface Create a surface
SDL.loadBMP Load a BMP file as a surface
SDL.loadBMP_RW Load a BMP file as a surface from a RWops

Texture

The object which holds SDL_Texture.

Objects

Object Description
Texture The texture object

Types

Type Description
SDL.textureAccess The texture access
SDL.textureModulate The texture modulation

Thread

The threading API is very specific to Lua-SDL2. Because Lua is not really thread safe, a thread is created within a new Lua context and does not share any data nor functions from the parent process.

Objects

Object Description
Thread The thread object

Functions

Function Description
SDL.createThread Create a thread

Timer

This category allows you to set up timers.

Types

Type Description
TimerCallback The timer callback function

Objects

Object Description
Timer The timer object

Functions

Function Description
SDL.addTimer Add a timer
SDL.delay Suspend the process
SDL.getPerformanceCounter Get the performance counter
SDL.getPerformanceFrequency Get the performance frequency
SDL.getTicks Get the number of milliseconds elapsed since startup

Window

Objects

Object Description
Window The window object

Types

Type Description
DisplayMode The display mode table

Tables

Table Description
SDL.window Window flags

Functions

Function Description
SDL.createWindow Create a window

SDL.clearError

Use this function to clear any previous error message.

Function

SYNOPSIS

function SDL.clearError()

SDL.clearHints

Use this function to clear all hints.

Function

SYNOPSIS

function SDL.clearHints()

SDL.convertAudio

Convert some audio data.

The input table may or must have the following fields:

The output table may or will have the following fields:

Function

SYNOPSIS

output, err = function SDL.convertAudio(input)

ARGUMENTS

RETURNS


SDL.createColorCursor

Create a cursor.

Function

SYNOPSIS

cursor, err = function SDL.createColorCursor(s, hotx, hoty)

ARGUMENTS

RETURNS


SDL.createCursor

Create a cursor.

Function

SYNOPSIS

cursor, err = function SDL.createCursor(data, mask, w, h, x, y)

ARGUMENTS

RETURNS


SDL.createRGBSurface

Create a surface

Function

SYNOPSIS

surface, err = function SDL.createRGBSurface(width, height, depth, rmask, gmask, bmask, amask)

ARGUMENTS

RETURNS

EXAMPLE

local s, err = SDL.createRGBSurface(100, 100, 32)

SDL.createRenderer

Create a renderer.

Function

SYNOPSIS

rdr, err = function SDL.createRenderer(win, index, flags)

ARGUMENTS

RETURNS


SDL.createSoftwareRenderer

Create a software renderer.

Function

SYNOPSIS

rdr, err = function SDL.createSoftwareRenderer(surface)

ARGUMENTS

RETURNS


SDL.createThread

Create a separate thread of execution. It is highly recommended to not discard the value of the function and to wait the thread before exiting.

You can pass optional parameters to the thread source except userdata and functions.

Function

SYNOPSIS

function SDL.createThread(name, path, ...)

ARGUMENTS

RETURNS

EXAMPLES

local t = SDL.createThread("name", "drawing.lua")

Function

SYNOPSIS

function SDL.createThread(name, func, ...)

ARGUMENTS

RETURNS

EXAMPLES

local function job()
    while true do
        print("...")
    end
end

local t = SDL.createThread("name", job)

SDL.createWindow

Use this function to create a window with the specified position, dimensions, and flags.

Function

SYNOPSIS

win, err = function SDL.createWindow(args)

ARGUMENTS

RETURNS

REMARKS

The table args may have the following fields:

EXAMPLES

local win, err = SDL.createWindow {
    title  = "My super game v0.1",
    width  = 600,
    height = 320,
    flags  = { SDL.window.Fullscreen }
}

if not win then
    error(err)
end

SDL.delay

Suspend the process for a specific amount of milliseconds.

Function

SYNOPSIS

function SDL.delay(ms)

ARGUMENTS


SDL.disableScreenSaver

Disable the screen saver.

Function

SYNOPSIS

function SDL.displayScreenSaver()

SDL.enableScreenSaver

Enable the screen saver.

Function

SYNOPSIS

function SDL.enableScreenSaver()

SDL.eventState

Use this function to set the state of processing events by type.

Function

SYNOPSIS

function SDL.eventState(type, state)

ARGUMENTS

RETURNS


SDL.filterEvents

Filter all events in the queue.

Function

SYNOPSIS

function SDL.filterEvents(fn)

ARGUMENTS

REMARKS

The function must have the following signature:

keep = function (event)

Where arguments are:

And return values are:


SDL.flushEvent

Use this function to clear events from the event queue.

Function

SYNOPSIS

function SDL.flushEvent(type)

ARGUMENTS

SEE ALSO

SDL.flushEvents


SDL.flushEvents

Use this function to clear events from the event queue.

Function

SYNOPSIS

function SDL.flushEvents(min, max)

ARGUMENTS

SEE ALSO

SDL.flushEvent


SDL.getAudioDeviceName

Get an audio device name.

Function

SYNOPSIS

name, err = function SDL.getAudioDeviceName(index, capture)

ARGUMENTS

RETURNS


SDL.getAudioDriver

Get an audio driver name.

Function

SYNOPSIS

name, err = function SDL.getAudioDriver(index)

ARGUMENTS

RETURNS


SDL.getAudioStatus

Get the audio status.

Function

SYNOPSIS

status = function SDL.getAudioStatus()

RETURNS


SDL.getBasePath

Available since 2.0.3-2

Use this function to get the directory where the application was run from. This is where the application data directory is.

Function

SYNOPSIS

path, err = function SDL.getBasePath()

RETURNS


SDL.getChannel

Get a channel. Creates it if does not exist.

Function

SYNOPSIS

channel, err = function SDL.getChannel(name)

ARGUMENTS

RETURNS


SDL.getClosestDisplayMode

Get the closest display mode.

Function

SYNOPSIS

mode, err = function SDL.getClosestDisplayMode(index, mode)

ARGUMENTS

RETURNS


SDL.getCurrentAudioDriver

Get the current audio driver name.

Function

SYNOPSIS

name, err = function SDL.getCurrentAudioDriver()

RETURNS


SDL.getCurrentDisplayMode

Get the current display mode.

Function

SYNOPSIS

mode, err = function SDL.getCurrentDisplayMode(index)

ARGUMENTS

RETURNS


SDL.getCurrentVideoDriver

Get the current video driver

Function

SYNOPSIS

name = function SDL.getCurrentVideoDriver()

RETURNS


SDL.getCursor

Get the cursor object.

Function

SYNOPSIS

cursor, err = function SDL.getCursor()

RETURNS


SDL.getDesktopDisplayMode

Get the desktop display mode.

Function

SYNOPSIS

mode, err = function SDL.getDesktopDisplayMode(index)

ARGUMENTS

RETURNS


SDL.getDisplayBounds

Get the display bounds.

Function

SYNOPSIS

rect = function SDL.getDisplayBounds(index)

ARGUMENTS

RETURNS


SDL.getDisplayMode

Get the display mode.

Function

SYNOPSIS

mode, err = function SDL.getDisplayMode(index, modeIndex)

ARGUMENTS

RETURNS


SDL.getError

Use this function to retrieve a message about the last error that occurred.

Function

SYNOPSIS

err = function SDL.getError()

RETURNS


SDL.getHint

Use this function to get the value of a hint.

Function

SYNOPSIS

function SDL.getHint(name)

ARGUMENTS

RETURNS


SDL.getKeyFromName

Get the key from a name.

Function

SYNOPSIS

key = function SDL.getKeyFromName(name)

ARGUMENTS

RETURNS


SDL.getKeyFromScancode

Get a key from a scancode.

Function

SYNOPSIS

key = function SDL.getKeyFromScancode(scancode)

ARGUMENTS

RETURNS


SDL.getKeyName

Get the key name.

Function

SYNOPSIS

name = function SDL.getKeyName(key)

ARGUMENTS

RETURNS


SDL.getKeyboardFocus

Get the window with keyboard focus.

Function

SYNOPSIS

win = function SDL.getKeyboardFocus()

RETURNS


SDL.getKeyboardState

Get the keyboard state. This function returns a userdata with a specific __index metamethod which each time it is indexed with a valid SDL.key it returns true if the key is currently pressed.

Function

SYNOPSIS

state = function SDL.getKeyboardState()

RETURNS

EXAMPLES

local state = SDL.getKeyboardState()

while true do
    SDL.pumpEvents()
    if state[SDL.key.Return] then
        print("Return is pressed")
    end
end

SDL.getModState

Get the keyboard modifiers. Returns a table with all modifiers enabled.

Function

SYNOPSIS

mod = function SDL.getModState()

RETURNS

EXAMPLE

local mod = SDL.getModstate()

-- Test for ctrl alt modifiers
if mod[SDL.keymod.LeftControl] and mod[SDL.keymod.LeftAlt] then
    print("Almost ctrl-alt-del")
end

SDL.getMouseFocus

Use this function to get the window which currently has mouse focus.

Function

SYNOPSIS

function SDL.getMouseFocus()

RETURNS


SDL.getMouseState

Use this function to retrieve the current state of the mouse.

Function

SYNOPSIS

state, x, y = function SDL.getMouseState()

RETURNS

EXAMPLES

local state, x, y = SDL.getMouseState()

-- Check for buttons left and right
if state[SDL.mouseMask.Left] then
    print("Left is pressed")
end
if state[SDL.mouseMask.Right] then
    print("Right is pressed")
end

print("x = " .. x)
print("y = " .. y)

SDL.getNumAudioDevices

Get the number of audio devices.

Function

SYNOPSIS

num = function SDL.getNumAudioDevices(capture)

ARGUMENTS

RETURNS


SDL.getNumAudioDrivers

Get the number of audio drivers.

Function

SYNOPSIS

num = function SDL.getNumAudioDrivers()

RETURNS


SDL.getNumDisplayModes

Get the number of display modes.

Function

SYNOPSIS

num, err = function SDL.getNumDisplayModes(index)

ARGUMENTS

RETURNS


SDL.getNumRenderDrivers

Get the number of rendering drivers.

Function

SYNOPSIS

num = function SDL.getNumRenderDrivers()

RETURNS


SDL.getNumVideoDisplays

Get the number of displays.

Function

SYNOPSIS

num, err = function SDL.getNumVideoDisplays()

RETURNS


SDL.getNumVideoDrivers

Get the number of video drivers.

Function

SYNOPSIS

num, err = function SDL.getNumVideoDrivers()

RETURNS


SDL.getPerformanceCounter

Get the performance counter.

Function

SYNOPSIS

counter = function SDL.getPerformanceCounter()

h3. RETURNS

SDL.getPerformanceFrequency

Get the performance frequency.

Function

SYNOPSIS

frequency = function SDL.getPerformanceFrequency()

ARGUMENTS

RETURNS


SDL.getPlatform

Use this function to get the name of the platform.

Function

SYNOPSIS

name = function SDL.getPlatform()

RETURNS


SDL.getPowerInfo

Get the current power state.

Function

SYNOPSIS

state, seconds, percentage = function SDL.getPowerInfo()

RETURNS

EXAMPLES

local state, secs, pct = SDL.getPowerInfo()

if state == SDL.powerState.OnBattery then
    print("Running on battery")
    print(string.format("%d seconds left", secs))
end

SDL.getPrefPath

Available since 2.0.3-2

Use this function to get the "pref dir". This is meant to be where the application can write personal files (Preferences and save games, etc.) that are specific to the application. This directory is unique per user and per application.

Function

SYNOPSIS

path, err = SDL.getPrefPath(organization, application)

ARGUMENTS

RETURNS


SDL.getRelativeMouseMode

Use this function to query whether relative mouse mode is enabled.

Function

SYNOPSIS

function SDL.getRelativeMouseMode()

RETURNS


SDL.getRelativeMouseState

Use this function to retrieve the relative state of the mouse.

Function

SYNOPSIS

function SDL.getMouseState()

RETURNS

SEE ALSO

SDL.getMouseState


SDL.getRenderDriverInfo

Get the rendering driver info.

Function

SYNOPSIS

info, err = function SDL.getRenderDriverInfo(index)

ARGUMENTS

RETURNS


SDL.getScancodeFromKey

Get a scancode from a key.

Function

SYNOPSIS

scancode = function SDL.getScancodeFromKey(key)

ARGUMENTS

RETURNS


SDL.getScancodeFromName

Get the scancode from name.

Function

SYNOPSIS

scancode = function SDL.getScancodeFromName(name)

ARGUMENTS

RETURNS


SDL.getScancodeName

Get the scancode name.

Function

SYNOPSIS

name = function SDL.getScancodeName(scancode)

ARGUMENTS

RETURNS


SDL.getTicks

Get the time elapsed since the startup.

Function

SYNOPSIS

ticks = function SDL.getTicks()

RETURNS


SDL.getVideoDriver

Get the video driver name.

Function

SYNOPSIS

name = function SDL.getVideoDriver(index)

ARGUMENTS

RETURNS


SDL.glCreateContext

Create a GL context.

Function

SYNOPSIS

ctx, err = function SDL.glCreateContext(win)

ARGUMENTS

RETURNS


SDL.glDeleteContext

Delete the GL context.

Function

SYNOPSIS

function SDL.glDeleteContext(ctx)

ARGUMENTS


SDL.glExtensionSupported

Check if an extension is supported.

Function

SYNOPSIS

ret = function SDL.glExtensionSupported(name)

ARGUMENTS

RETURNS


SDL.glGetAttribute

Get a GL attribute

Function

SYNOPSIS

ret, err = function SDL.glGetAttribute(id)

ARGUMENTS

RETURNS


SDL.glGetCurrentContext

Get the current context.

Function

SYNOPSIS

ctx, err = function SDL.glGetCurrentContext()

RETURNS


SDL.glGetCurrentWindow

Get the current window.

Function

SYNOPSIS

win, err = function SDL.glGetCurrentWindow()

RETURNS


SDL.glGetDrawableSize

Get the drawable size.

Function

SYNOPSIS

w, h = function SDL.glGetDrawableSize()

RETURNS


SDL.glGetSwapInterval

Get the swap interval

Function

SYNOPSIS

interval = function SDL.glGetSwapInterval()

RETURNS


SDL.glMakeCurrent

Make the window and context current.

Function

SYNOPSIS

ret, err = function SDL.glMakeCurrent(win, ctx)

ARGUMENTS

RETURNS


SDL.glSetAttribute

Set a GL attribute

Function

SYNOPSIS

ret, err = function SDL.glSetAttribute(id, value)

ARGUMENTS

RETURNS


SDL.glSetSwapInterval

Set the swap interval.

Function

SYNOPSIS

ret, err = function SDL.glSetSwapInterval(interval)

ARGUMENTS

RETURNS


SDL.glSwapWindow

Update the window.

Function

SYNOPSIS

function SDL.glSwapWindow(win)

ARGUMENTS


SDL.hapticOpen

Open a haptic device.

Function

SYNOPSIS

ht, err = function SDL.hapticOpen(index)

ARGUMENTS

RETURNS


SDL.hapticOpenFromJoystick

Open a haptic device from a joystick.

Function

SYNOPSIS

ht, err = function SDL.hapticOpenFromJoystick(joy)

ARGUMENTS

RETURNS


SDL.hapticOpenFromMouse

Open a haptic device from mouse.

Function

SYNOPSIS

ht, err = function SDL.hapticOpenFromMouse()

RETURNS


SDL.hapticOpened

Check if a haptic device is opened.

Function

SYNOPSIS

status = function SDL.hapticOpened(index)

ARGUMENTS

RETURNS


SDL.hasEvent

Use this function to check for the existence of certain event types in the event queue.

Function

SYNOPSIS

function SDL.hasEvent(type)

ARGUMENTS

RETURNS


SDL.hasEvents

Use this function to check for the existence of a range of event types in the event queue.

Function

SYNOPSIS

function SDL.hasEvents(min, max)

ARGUMENTS

RETURNS


SDL.init

Initialize SDL.

Function

SYNOPSIS

ret, err = function SDL.init(flags)

ARGUMENTS

RETURNS


SDL.initSubSystem

Works like SDL.init but bypasses some internal checks.

Function

SYNOPSIS

ret, err = function SDL.initSubSystem(flags)

ARGUMENTS

RETURNS

SEE ALSO

SDL.init


SDL.isScreenSaverLoaded

Check if the screen saver is loaded.

Function

SYNOPSIS

ret = function SDL.isScreenSaverLoaded()

RETURNS


SDL.joystickEventState

Enable or disable joystick events.

Function

SYNOPSIS

ret, err = function SDL.joystickEventState(state)

ARGUMENTS

RETURNS


SDL.joystickIsHaptic

Check if the joystick is an haptic device.

Function

SYNOPSIS

status, err = function SDL.joystickIsHaptic(joy)

ARGUMENTS

RETURNS


SDL.joystickNameForIndex

Get the joystick name from an index.

Function

SYNOPSIS

name, err = function SDL.joystickNameForIndex(index)

ARGUMENTS

RETURNS


SDL.joystickOpen

Open a joystick by index.

Function

SYNOPSIS

joy, err = function SDL.joystickOpen(index)

ARGUMENTS

RETURNS


SDL.joystickUpdate

Update the joystick events.

Function

SYNOPSIS

function SDL.joystickUpdate()

SDL.loadBMP

Load a BMP file as a surface.

Function

SYNOPSIS

surface, err = function SDL.loadBMP(file)

ARGUMENTS

RETURNS


SDL.loadBMP_RW

Load a BMP file as a surface from a RWops.

Function

SYNOPSIS

surface, err = function SDL.loadBMP_RW(rw)

ARGUMENTS

RETURNS


SDL.loadWAV

Load a WAV file from a path.

Function

SYNOPSIS

data, err = function SDL.loadWAV(path)

ARGUMENTS

RETURNS


SDL.loadWAV_RW

Load a WAV file from a RWops.

Function

SYNOPSIS

data, err = function SDL.loadWAV_RW(rw)

ARGUMENTS

RETURNS


SDL.log

Use this function to log a message with application category and info priority.

Function

SYNOPSIS

function SDL.log(msg)

ARGUMENTS


SDL.logCritical

Use this function to log a message with critial priority.

Function

SYNOPSIS

function SDL.logCritical(category, msg)

ARGUMENTS


SDL.logDebug

Use this function to log a message with debug priority.

Function

SYNOPSIS

function SDL.logDebug(category, msg)

ARGUMENTS


SDL.logError

Use this function to log a message with error priority

Function

SYNOPSIS

function SDL.logError(category, msg)

ARGUMENTS


SDL.logGetOutputFunction

Get the current Lua output function used for any logging.

Function

SYNOPSIS

f = function SDL.logGetOutputFunction()

RETURNS


SDL.logGetPriority

Use this function to get the priority of a particular log category.

Function

SYNOPSIS

priority = function SDL.logGetPriority(category)

ARGUMENTS

RETURNS


SDL.logInfo

Use this function to log a message with info priority.

Function

SYNOPSIS

function SDL.logInfo(category, msg)

ARGUMENTS


SDL.logMessage

Use this function to log a message with specific category and priority.

Function

SYNOPSIS

function SDL.logMessage(category, priority, msg)

ARGUMENTS


SDL.logResetPriorities

Use this function to reset all priorities to default.

Function

SYNOPSIS

function SDL.logResetPriorities()

SDL.logSetAllPriority

Use this function to set the priority of all log categories.

Function

SYNOPSIS

function SDL.logSetAllPriority(priority)

ARGUMENTS


SDL.logSetOutputFunction

Use this function to replace the default log output function with one of your own.

Function

SYNOPSIS

function SDL.logSetOutputFunction(output)

ARGUMENTS

REMARKS

The output function must have the following signature:

function (category, priority, message)

Where arguments are:

EXAMPLES

SDL.logSetOutputFunction(
    function (category, priority, message)
        -- Do what you want with category, priority and message
    end
)

SDL.logVerbose

Use this function to log a message with verbose priority.

Function

SYNOPSIS

function SDL.logVerbose(category, msg)

ARGUMENTS


SDL.logWarn

Use this function to log a message with warning priority.

Function

SYNOPSIS

function SDL.logWarn(category, msg)

ARGUMENTS


SDL.mixAudio

Mix some audio.

Function

SYNOPSIS

data, err = function SDL.mixAudio(data, volume)

ARGUMENTS

RETURNS


SDL.mixAudioFormat

Mix some audio with a format.

Function

SYNOPSIS

data, err = function SDL.mixAudioFormat(data, format, volume)

ARGUMENTS

RETURNS


SDL.mouseIsHaptic

Check if the mouse is an haptic device.

Function

SYNOPSIS

status = function SDL.mouseIsHaptic()

RETURNS


SDL.numHaptics

Get the number of haptic devices.

Function

SYNOPSIS

num, err = function SDL.numHaptics()

RETURNS


SDL.numJoysticks

Get the number of joysticks available.

Function

SYNOPSIS

num, err = function SDL.numJoysticks()

RETURNS


SDL.openAudio

Open the audio. It use the same specs as SDL.openAudioDevice except that fields iscapture, device and allowchanges are not needed.

Function

SYNOPSIS

dev, err = function SDL.openAudio(spec)

ARGUMENTS

RETURNS

SEE ALSO


SDL.openAudioDevice

Open an audio device.

The spec table may or must have the following fields:

Function

SYNOPSIS

dev, err = function SDL.openAudioDevice(spec)

ARGUMENTS

RETURNS


SDL.peepEvents

Use this function to check the event queue for messages and optionally return them.

Function

SYNOPSIS

function SDL.peepEvents(count, action [, min [, max]])

ARGUMENTS

RETURNS

EXAMPLES

--
-- This will get all events without removing it from the queue only if they
-- match the mouse events.
--

local events = SDL.peepEvents(16, SDL.eventAction.Peek, SDL.event.MouseMotion, SDL.event.MouseWheel)

for _, e in ipairs(events) do
    print(tostring(e.type))
end

SDL.pollEvent

Use this function to poll for currently pending events. This function is implemented as an iterator.

Function

SYNOPSIS

function SDL.pollEvent()

RETURNS

EXAMPLES

--
-- This is the recommended way of handling events
--
local running = true
while running do
    for e in SDL.pollEvent() do
        if e.type == SDL.event.Quit then
            running = false
        end
    end
end

SEE ALSO

SDL.waitEvent


SDL.pumpEvents

Use this function to pump the event loop, gathering events from the input devices.

Function

SYNOPSIS

function SDL.pumpEvents()

SDL.quit

Quit everything. Should only be called just before closing the application.

Function

SYNOPSIS

function SDL.quit()

SDL.quitRequested

Use this function to see whether an SDL_QUIT event is queued.

Function

SYNOPSIS

function SDL.quitRequested()

RETURNS


SDL.quitSubSystem

Quit some subsystems.

Function

SYNOPSIS

function SDL.quitSubSystem(flags)

ARGUMENTS


SDL.registerEvents

Use this function to allocate a set of user-defined events, and return the beginning event number for that set of events.

Function

SYNOPSIS

function SDL.registerEvents(num)

ARGUMENTS

RETURNS


SDL.setCursor

Set the cursor.

Function

SYNOPSIS

function SDL.setCursor(c)

SDL.setError

Use this function to set the SDL error string.

Function

SYNOPSIS

function SDL.setError(error)

ARGUMENTS


SDL.setEventFilter

Add an event filter, it is called before an event is added to the queue.

Function

SYNOPSIS

filter = function SDL.setEventFilter(fn)

ARGUMENTS

RETURNS

REMARKS

The function must have the following signature:

status = function (event)

Where arguments are:

And return values are:


SDL.setHint

Use this function to set a hint with normal priority.

Function

SYNOPSIS

function SDL.setHint(name, value)

ARGUMENTS

RETURNS


SDL.setModState

Set the modifiers state.

Function

SYNOPSIS

function SDL.setModState(state)

ARGUMENTS


SDL.setRelativeMouseMode

Use this function to set the relative mouse mode.

Function

SYNOPSIS

function SDL.setRelativeMouseMode(mode)

ARGUMENTS

RETURNS


SDL.setTextInputRect

Set the input text rectangle.

Function

SYNOPSIS

function SDL.setTextInputRect(rect)

ARGUMENTS


SDL.showCursor

Use this function to toggle whether or not the cursor is shown.

Function

SYNOPSIS

function SDL.showCursor(mode)

ARGUMENTS

RETURNS


SDL.startTextInput

Start text input.

Function

SYNOPSIS

function SDL.startTextInput()

SDL.stopTextInput

Stop text input.

Function

SYNOPSIS

function SDL.stopTextInput()

SDL.videoInit

Initialize the video system.

Function

SYNOPSIS

ret, err = function SDL.videoInit(name)

ARGUMENTS

RETURNS


SDL.videoQuit

Quit the video system.

Function

SYNOPSIS

function SDL.videoQuit()

SDL.waitEvent

Wait for an event with an optional timeout.

Function

SYNOPSIS

function SDL.waitEvent([timeout])

ARGUMENTS

RETURNS

EXAMPLES

Wait for an event with a timeout of 1 second.

local e = SDL.waitEvent(1000)

Wait for an event indefinitely.

local e = SDL.waitEvent()

SDL.wasInit

Check which subsystems have been initialized.

Function

SYNOPSIS

modules, err = function SDL.wasInit(flags)

ARGUMENTS

RETURNS

EXAMPLE

local modules = SDL.wasInit()

if not modules[SDL.flags.Audio] then
    error("Need audio module")
end

Supported features

Lua-SDL2 tries to be as close as possible to the C API. However, it uses object orientation whenever possible, e.g SDL_Texture, SDL_Window and such.

The following list is not implemented in Lua-SDL2:

Lua versions

Lua-SDL2 has been tested on the following Lua versions:

Note: Lua-SDL does not set any globals, you must use the returned value of require.


Font:ascent

Get the maximum pixel ascent of all glyphs.

Method

SYNOPSIS

size = function Font:ascent()

RETURNS


Font:descent

Get the maximum pixel descent of all glyphs.

Method

SYNOPSIS

size = function Font:descent()

RETURNS


Font:faceFamilyName

Get the font face name.

Method

SYNOPSIS

name = function Font:faceFamilyName()

RETURNS


Font:faceIsFixedWidth

Check if a font is fixed width.

Method

SYNOPSIS

result = function Font:faceIsFixedWidth()

RETURNS


Font:faceStyleName

Get the face style name.

Method

SYNOPSIS

name = function Font:faceStyleName()

RETURNS


Font:faces

Get the number of faces in the font.

Method

SYNOPSIS

num = function Font:faces()

RETURNS


Font:getHinting

Get the current hinting.

Method

SYNOPSIS

hinting = function Font:getHinting()

RETURNS


Font:getKerning

Get the kerning setting.

Method

SYNOPSIS

value = function Font:getKerning()

RETURNS


Font:getOutline

Get the outline size.

Method

SYNOPSIS

outline = function Font:getOutline()

RETURNS


Font:getStyle

Get the font style.

Method

SYNOPSIS

style = function Font:getStyle

RETURNS


Font:glyphIsProvided

Check if a unicode character is provided.

Method

SYNOPSIS

result = function Font:glyphIsProvided(ch)

ARGUMENTS

RETURNS


Font:glyphMetrics

Get the size of a unicode character. The table returned has the following fields:

Method

SYNOPSIS

size, err = function Font:glyphMetrics(ch)

ARGUMENTS

RETURNS


Font:height

Get the maximum size of all glyphs.

Method

SYNOPSIS

size = function Font:height()

RETURNS


ttf.fontHinting

Font hinting.

Enum

SYNOPSIS

ttf.fontHinting = {
    Normal,
    Light,
    Mono,
    None
}

VALUES


Font:lineSkip

Get the recommended pixel height for new lines.

Method

SYNOPSIS

size = function Font:lineSkip()

RETURNS


Font

Representation of TTF_Font as an object.

Object

Methods

Method Description
Font:getStyle Get the font style
Font:setStyle Set the font style
Font:getOutline Get the outline
Font:setOutline Set the outline
Font:getHinting Get the hinting
Font:setHinting Set the hinting
Font:getKerning Get the kerning
Font:setKerning Set the kerning
Font:height Get the height
Font:ascent Get the ascent
Font:descent Get the descent
Font:lineSkip Get the line skip
Font:faces Get the number of faces
Font:faceIsFixedWidth Check if the font face is fixed width
Font:faceFamilyName Get the font face family name
Font:faceStyleName Get the font face style name
Font:glyphIsProvided Check if a character is provided
Font:glyphMetrics Get a character size
Font:sizeText Compute the size of an ascii string
Font:sizeUtf8 Compute the size of a UTF-8 string
Font:sizeUnicode Compute the size of an unicode table
Font:renderText Render an ascii string
Font:renderUtf8 Render a UTF-8 string
Font:renderUnicode Render an unicode table

Font:renderText

Render a text and create a SDL_Surface.

Method

SYNOPSIS

s, err = function Font:renderText(text, style, fg, bg)

ARGUMENTS

RETURNS


Font:renderUnicode

Render a unicode table and create a SDL_Surface.

Method

SYNOPSIS

s, err = function Font:renderUnicode(seq, style, fg, bg)

ARGUMENTS

RETURNS

EXAMPLE

-- "Gérard" 
local s = { 'G', 233, 'r', 'a', 'r', 'd' }

-- f is a font loaded with ttf.openFont
local s = f:renderUnicode(s)

Font:renderUtf8

Render a text and create a SDL_Surface.

Method

SYNOPSIS

s, err = function Font:renderUtf8(text, style, fg, bg)

ARGUMENTS

RETURNS


Font:setHinting

Set the font hinting.

Method

SYNOPSIS

function Font:setHinting(hinting)

ARGUMENTS


Font:setKerning

Set the kerning setting.

Method

SYNOPSIS

function Font:setKerning(value)

ARGUMENTS


Font:setOutline

Set the outline size.

Method

SYNOPSIS

function Font:setOutline(outline)

ARGUMENTS


Font:setStyle

Set the font style.

Method

SYNOPSIS

function Font:setStyle(style)

ARGUMENTS


Font:sizeText

Compute the text size.

Method

SYNOPSIS

w, h, err = function Font:sizeText(text)

ARGUMENTS

RETURNS


Font:sizeUnicode

Compute the text size.

Method

SYNOPSIS

w, h, err = function Font:sizeText(seq)

ARGUMENTS

RETURNS

EXAMPLE

-- "Gérard" 
local s = { 'G', 233, 'r', 'a', 'r', 'd' }

-- f is a font loaded with ttf.openFont
local w, h = f:sizeUnicode(s)

Font:sizeUtf8

Compute the text size.

Method

SYNOPSIS

w, h, err = function Font:sizeText(text)

ARGUMENTS

RETURNS


ttf.fontStyle

The font style.

Enum

SYNOPSIS

ttf.fontStyle = {
    Bold,
    Italic,
    Underline,
    StrikeThrough
}

VALUES


ttf.init

Initialize the module.

Function

SYNOPSIS

ret, err = function ttf.init()

RETURNS


ttf.open

Open a font by path.

Function

SYNOPSIS

f, err = function ttf.open(path)

ARGUMENTS

RETURNS

ttf.open

Open a font by RWops.

Function

SYNOPSIS

f, err = function ttf.open(rwops)

ARGUMENTS

RETURNS


ttf.quit

Close the module.

Function

SYNOPSIS

function ttf.quit()

Tutorial 01 - Initialization

In this tutorial, we will simply loads the SDL module and initialize the library.

Loading the module

To load the module, you just need to call the require function. This only loads the module, it does not initialize the library. However, if some internal code fails, this raises a Lua error.

local SDL = require "SDL" 

Obviously, you can use a different table name.

Note: Lua-SDL2 does not set any globals.

Initialize the library

The library must be now initialized with SDL.init and passing one or more SDL.flags. In our example, we want to load the video and audio subsystem.

local ret, err = SDL.init {
    SDL.flags.Video,
    SDL.flags.Audio
}

if not ret then
    error(err)
end

If the load fail, ret will be set to false and err will contain the error message.

Showing the version

Now that we have loaded the library, show the version implemented. This is the SDL version, not Lua-SDL version.

-- Show the version
print(string.format("SDL %d.%d.%d",
    SDL.VERSION_MAJOR,
    SDL.VERSION_MINOR,
    SDL.VERSION_PATCH
))

Quit

When you're done, calls SDL.quit

SDL.quit()

Full example

Download 01-initialization.tgz


Tutorial 02 - Opening a window

Open a window and close it. Don't forget to initialize the library as described in Tutorial 01 - Initialization.

Create the window

To create the window, use the the SDL.createWindow function. It takes a table with optional parameters.

local win, err = SDL.createWindow {
        title   = "02 - Opening a window",      -- optional
        width   = 320,                          -- optional
        height  = 320,                          -- optional
        flags   = { SDL.window.Resizable }      -- optional
        x       = 126,                          -- optional
        y       = 126,                          -- optional
}

if not win then
        error(err)
end

As you may notice, all fields are completely optional.

Note: setting the initial coordinates x and y is a bad practice and some window manager and system may just ignore it.

Full example

Download 02-window.tgz


Tutorial 03 - Polling events

There are many ways to poll input events. You can use blocking functions like SDL.waitEvent or non blocking functions like SDL.pollEvent. The first one will blocks indefinitely until an event comes while the second iterate over all ready events.

Except if you really need synchronous scenarios, one should use SDL.pollEvent.

Reading events

To read events, just calls SDL.pollEvent in a for loop. It returns a table with the information about the event. See Event for more information about the events.

while running do
        --
        -- Iterate over all events, this function does not block.
        --
        for e in SDL.pollEvent() do
                if e.type == SDL.event.Quit then
                        running = false
                elseif e.type == SDL.event.KeyDown then
                        print(string.format("key down: %d -> %s", e.keysym.sym, SDL.getKeyName(e.keysym.sym)))
                elseif e.type == SDL.event.MouseWheel then
                        print(string.format("mouse wheel: %d, x=%d, y=%d", e.which, e.x, e.y))
                elseif e.type == SDL.event.MouseButtonDown then
                        print(string.format("mouse button down: %d, x=%d, y=%d", e.button, e.x, e.y))
                elseif e.type == SDL.event.MouseMotion then
                        print(string.format("mouse motion: x=%d, y=%d", e.x, e.y))
                end
        end
end

In that example, we check the type of event and then we used the fields available for the more common events.

Full example

Download 03-events.tgz


Tutorial 04 - Drawing an image

Drawing an image is best done by using the SDL_image module. It can loads several famous formats.

Loading SDL_image

To load SDL_image, please be sure that you compiled SDL_image with Lua-SDL2. They are built as separate libraries and needs to be loaded by hand with require

local image = require "SDL.image" 

Initializing SDL_image

To initialize SDL_image, calls image.init and pass one or more image.flags for the desired formats. The functions returns a table with loaded formats and an optional error message.

local formats, ret, err = image.init { image.flags.PNG }

if not formats[image.flags.PNG] then
    error(err)
end

Load the image

To load an image, you can use image.load and specify the image by path. This functions returns a Surface.

local img, ret = image.load("Lua-SDL2.png")
if not img then
    error(err)
end

Create a renderer

To create a 2D accelerated context, one should create a Renderer.

local rdr, err = SDL.createRenderer(win, 0, 0)
if not rdr then
    error(err)
end

Convert to texture

Before rendering, you need to convert the surface to a Texture

img = rdr:createTextureFromSurface(img)

Draw to renderer

Now that you converted the surface to a texture you can copy it.

for i = 1, 50 do
    rdr:setDrawColor(0xFFFFFF)
    rdr:clear()
    rdr:copy(img)
    rdr:present()

    SDL.delay(100)
end

Expected output

Full example

Download 04-drawing.tgz


Tutorial 05 - Playing sound

Playing sound is very easy with the SDL_mixer API.

Loading SDL_mixer

Just like other additional modules, SDL_mixer must be loaded separately.

local mixer = require "SDL.mixer" 

Initialize SDL_mixer

Open the audio device with standard defaults.

local ret, err = mixer.openAudio(44100, SDL.audioFormat.S16, 2, 1024)

if not ret then
    error(err)
end

Load the sound

Now we can load a chunk and play it to the first channel.

local sound = mixer.loadWAV("gun.wav")

if not sound then
    error(err)
end

Play the sound

Play the sound on the first channel.

sound:playChannel(1)

-- Let the sound play
SDL.delay(5000)

Full example

Download 05-sound.tgz


Tutorial 06 - Writing text

Writing text to the screen is easy with SDL_ttf. Please see Tutorial 04 - Drawing an image to initialize the window and renderer.

Load the SDL_ttf library

As always, load the library separately.

local ttf = require "SDL.ttf" 

Initialize the library

We may now want to load the library.

local ret, err = ttf.init()

if not ret then
    error(err)
end

Load a font

Now that we loaded the SDL_ttf library, we must open a font before writing text. You need to specify the path to the .ttf file.

local font, err = ttf.openFont("DejaVuSans.ttf", 10)

if not font then
    error(err)
end

Render the text

The function Font:renderUtf8 and friends creates surfaces which must be converted later.

local s, err = font:renderUtf8("Lua-SDL2", "solid", 0xFFFFFF)

if not s then
    error(err)
end

Convert and draw

Convert the surface to texture.

local text = rdr:createTextureFromSurface(s)

while true do
    rdr:clear()
    rdr:copy(text)
    rdr:present()
end

Expected output

Full example

Download 06-text.tgz


Tutorial 07 - Bouncing logo

The final tutorial expects you to have ran the previous tutorials. In this example, we will just bounce the Lua-SDL2 logo to the window borders.

Preparing variables

local running   = true
local graphics  = { }
local pos       = { }
local dir       = { 1, 1 }
local width     = 640
local height    = 480

Getting the logo size

Now we need to query the logo size to determine the initial position

local img, ret = image.load("Lua-SDL2.png")
if not img then
    error(err)
end

local logo, err = rdr:createTextureFromSurface(img)
if not logo then
    error(err)
end

-- Store in global graphics
graphics.win    = win
graphics.rdr    = rdr
graphics.logo   = logo

-- Get the size of the logo
local f, a, w, h = logo:query()

pos.x = width / 2 - w / 2
pos.y = height / 2 - h / 2
pos.w = 256
pos.h = 256

Main loop

In the main loop, we just increase the position and test if it goes to a border boundary, in that case we toggle the direction factor.

while running do
        for e in SDL.pollEvent() do
                if e.type == SDL.event.Quit then
                        running = false
                end
        end

        graphics.rdr:clear()
        graphics.rdr:copy(graphics.logo, nil, pos)
        graphics.rdr:present()

        pos.x = pos.x + dir[1]
        pos.y = pos.y + dir[2]

        if dir[1] > 0 and pos.x > width - 256 then
                dir[1] = -1
        elseif dir[1] < 0 and pos.x <= 0 then
                dir[1] = 1
        end

        if dir[2] > 0 and pos.y > height - 256 then
                dir[2] = -1
        elseif dir[2] < 0 and pos.y <= 0 then
                dir[2] = 1
        end

        SDL.delay(20)
end

Expected output

Full example

Download 07-bouncing.tgz


Lua-SDL2 2.0.3-1 (June 06, 2014)

Initial Lua-SDL release.


Lua-SDL2 2.0.3-2 (October 08, 2014)


Lua-SDL2 2.0.3-3 (January 03, 2015)

Lua-SDL2 2.0.3-3.1