Written from a line-by-line source review; the deterministic example outputs are from a real run.
Introduction
The sdl plugin provides the full surface of the SDL2 multimedia library: you can open a window, do pixel-level 2D graphics (rectangles, lines, textures), read events (keyboard, mouse, window close), play audio (WAV files or a synthesized tone), and load images as textures (BMP, plus PNG/JPG/WebP when SDL2_image is present). The plugin is handle-based: window, texture, WAV, and audio resources receive an integer identifier (a handle) that further operations refer to them by.
SDL2 at runtime (dlopen)
The plugin loads SDL2 and SDL2_image at runtime (like the other plugins), so they need not be linked at build time. The first sdl.Init or any other call requiring SDL2 automatically loads SDL2 and initializes the video, audio, and timer subsystems. Loading PNG/JPG/WebP image textures requires the presence of SDL2_image (libSDL2_image) at runtime; ImageRuntimeLoaded and Image*Supported report whether it is available.
Relationship to the opengl plugin
The sdl and opengl plugins can be used in parallel, but with different purposes: opengl provides a high-level 3D demonstration scene (rotating cube, textures, gl.* fixed-pipeline wrappers), and sdl provides the SDL2-based API for 2D graphics, audio, and events. The two have their OWN windows and state; you generally choose one or the other for your script, depending on whether you need 3D rendering or 2D multimedia.
Loading the plugin
plugin "../plugins/print/PrintPlugin"; plugin "../plugins/sdl2/Sdl2Plugin";
A typical flow — 2D window and drawing
i32 $win;
sdl.Init();
$win = sdl.OpenWindow("Demo", 800, 600);
while (sdl.PollQuit() == 0)
{
sdl.Clear($win, 20, 20, 30);
sdl.FillRect($win, 100, 100, 200, 150, 255, 80, 80);
sdl.Present($win);
}
sdl.CloseWindow($win);
sdl.Quit();What to know about every function (the basics)
The SDL2-requiring verbs automatically initialize SDL2 on the first call (Init/OpenWindow/Ticks/Delay/PumpEvents/PollEvent/PollQuit/OpenAudio/LoadWav/PlayWav/LoadTexture).
Window, texture, WAV, and audio resources receive a positive handle, which must be freed with the matching Close*.
The color components in 2D drawing are integers from 0..255 (R, G, B); the alpha channel in SetTextureAlpha is also 0..255.
Event handling has two modes: the SYNCHRONOUS PollEvent + Event* getters (on the main thread), or the ASYNCHRONOUS SetEventCallback (a background callback that subscribes to events).
ImageRuntimeLoaded and Image*Supported do NOT require SDL2 — they can be safely run as a load check.
An error (stopping the script) is caused by a wrong argument count or type, an invalid handle, and a failed SDL2 initialization.
How to read the signatures
windowId is the handle of an open window, textureId of a texture, audioId of an audio device, wavId of a loaded WAV file. The type after the -> arrow is the return type. For example, sdl.OpenWindow(title, width, height) -> int takes a string and two integers and returns a window handle.
Lifecycle and timing
Initializing and shutting down the SDL2 subsystems, plus timing helpers (elapsed time, waiting).
sdl.Init
sdl.Init() -> int
Initializes the SDL2 video, audio, and timer subsystems (if not yet initialized).
This function takes no arguments.
1 on success. A missing SDL2 or a failed Init causes a runtime error.
printf("%d\n", sdl.Init());1
The first step of an SDL2-using program. It is not strictly necessary to call: the other SDL2-requiring calls auto-initialize — but an explicit Init reveals immediately if SDL2 is not available.
sdl.Quit
sdl.Quit() -> int
Shuts down the SDL2 subsystems and releases the pending resources (windows, textures, audio).
This function takes no arguments.
Always 1.
printf("%d\n", sdl.Quit());1
Call at the end of the program. Open windows/textures/audio devices close automatically, but it is worth freeing them with your own Close* calls first, so the order is traceable.
sdl.Ticks
sdl.Ticks() -> int
Returns the milliseconds elapsed since SDL2 started.
This function takes no arguments.
The number of elapsed milliseconds.
printf("%d\n", sdl.Ticks());(an increasing millisecond value)
For simple time measurements or frame timing: the difference between two Ticks values gives the length of the given interval. Finer-grained and monotonic (not jumping back) compared to NowText.
sdl.Delay
sdl.Delay(ms) -> int
Waits for the given milliseconds (suspends the script).
| Parameter | Type | Description |
|---|---|---|
| ms | int | The wait time in milliseconds (non-negative). |
The given value (ms). A negative value causes a runtime error.
printf("%d\n", sdl.Delay(16));16
For frame pacing (for example 16 ms of waiting after each frame for ~60 fps), or for simple pausing. More accurate than many platforms' sleep, and gentler on the CPU.
Window and 2D drawing
Opening, closing a window, querying its size; drawing rectangles, lines, and presenting the drawing.
sdl.OpenWindow
sdl.OpenWindow(title, width, height) -> int
Opens an SDL2 window with the given title and size, and returns a window handle.
| Parameter | Type | Description |
|---|---|---|
| title | string | The window title. |
| width | int | The window width in pixels. |
| height | int | The window height in pixels. |
The window handle (a positive integer). A failed opening causes a runtime error.
i32 $win;
$win = sdl.OpenWindow("Demo", 800, 600);
// ... drawing + event handling ...
sdl.CloseWindow($win);(the window handle by which you call the rest of the 2D operations)
The first step of every 2D display. You pass the returned handle to Clear/FillRect/DrawLine/Present and the texture-drawing calls. Always close it at the end.
sdl.CloseWindow
sdl.CloseWindow(windowId) -> int
Closes the window and releases its associated resources.
| Parameter | Type | Description |
|---|---|---|
| windowId | int | The window handle to close. |
1 on success.
sdl.CloseWindow($win);
1
When a window is no longer needed, or the program stops. Close the textures bound to it separately first (CloseTexture), so the order is clean.
sdl.WindowWidth
sdl.WindowWidth(windowId) -> int
Returns the window's current width in pixels.
| Parameter | Type | Description |
|---|---|---|
| windowId | int | The window handle. |
The width in pixels.
printf("%d\n", sdl.WindowWidth($win));800
To query the window size — for example to fit the layout to the current size (after a user resize). WindowHeight is its height counterpart.
sdl.WindowHeight
sdl.WindowHeight(windowId) -> int
Returns the window's current height in pixels.
| Parameter | Type | Description |
|---|---|---|
| windowId | int | The window handle. |
The height in pixels.
printf("%d\n", sdl.WindowHeight($win));600
The counterpart of WindowWidth: together they give the current window size.
sdl.Clear
sdl.Clear(windowId, r, g, b) -> int
Clears the whole window area with the given RGB color.
| Parameter | Type | Description |
|---|---|---|
| windowId | int | The window handle. |
| r | int | Red (0..255). |
| g | int | Green (0..255). |
| b | int | Blue (0..255). |
1 on success.
sdl.Clear($win, 20, 20, 30);
(paints the window background dark blue)
The first drawing step of every frame: setting the background color. After it come FillRect/DrawLine/DrawTexture calls, then Present displays the whole image.
sdl.FillRect
sdl.FillRect(windowId, x, y, width, height, r, g, b) -> int
Draws a filled rectangle at the given position, size, and color.
| Parameter | Type | Description |
|---|---|---|
| windowId | int | The window handle. |
| x | int | The upper-left corner's X coordinate. |
| y | int | The upper-left corner's Y coordinate. |
| width | int | The rectangle width. |
| height | int | The rectangle height. |
| r | int | Red (0..255). |
| g | int | Green (0..255). |
| b | int | Blue (0..255). |
1 on success.
sdl.FillRect($win, 100, 100, 200, 150, 255, 80, 80);
(a red rectangle at the given place)
For UI elements (buttons, panels, background blocks), game tiles, or simple graphical elements. The coordinate system starts from the upper-left corner, growing downward/rightward.
sdl.DrawLine
sdl.DrawLine(windowId, x1, y1, x2, y2, r, g, b) -> int
Draws a straight line between two points with the given color.
| Parameter | Type | Description |
|---|---|---|
| windowId | int | The window handle. |
| x1 | int | The start point's X coordinate. |
| y1 | int | The start point's Y coordinate. |
| x2 | int | The end point's X coordinate. |
| y2 | int | The end point's Y coordinate. |
| r | int | Red (0..255). |
| g | int | Green (0..255). |
| b | int | Blue (0..255). |
1 on success.
sdl.DrawLine($win, 0, 0, 800, 600, 255, 255, 255);
(a white diagonal line)
For sketching, helper grids, contours, or simple geometric shapes. The lines are one pixel thick.
sdl.Present
sdl.Present(windowId) -> int
Displays all the pending drawings on the window (swapping the back buffer with the front).
| Parameter | Type | Description |
|---|---|---|
| windowId | int | The window handle. |
1 on success.
sdl.Clear($win, 0, 0, 0); sdl.FillRect($win, 10, 10, 50, 50, 255, 0, 0); sdl.Present($win);
(the image becomes visible)
The last step of every frame: only after this call does the drawn image appear. You typically use the Clear → Draw* → Present trio in a loop.
Event handling (synchronous)
Synchronous processing of the window's events (keyboard, mouse, quit) on the main thread, and querying the last event's data.
sdl.PumpEvents
sdl.PumpEvents() -> int
Fills the SDL2 internal event queue with operating-system events (without taking one).
This function takes no arguments.
1 on success.
sdl.PumpEvents();
(SDL2's internal queue is refreshed)
Usually need not be called explicitly — PollEvent / PollQuit does this automatically. It can be useful if you do not call Poll for a long time and want to make sure the window does not freeze.
sdl.PollEvent
sdl.PollEvent() -> int
Takes a pending event from the SDL2 queue and updates the state returned by the Event* getters.
This function takes no arguments.
The event type code (for example QUIT, KEYDOWN, MOUSEMOTION), or 0 if there was no event.
i32 $t;
$t = sdl.PollEvent();
if ($t > 0) { printf("event: %d, key=%d\n", $t,
sdl.EventKeyCode()); }(0, or the event's type code and data)
In the main loop: in every iteration you take one event, or get 0. The Event* getters give the data of the most recent event (key code, mouse position, wheel, etc.).
sdl.PollQuit
sdl.PollQuit() -> int
Checks whether a QUIT event has arrived (the window or the application was closed).
This function takes no arguments.
1 if a QUIT event arrived; otherwise 0.
while (sdl.PollQuit() == 0)
{
// ... frame ...
}0
As the main loop condition, the simplest pattern: while there is no QUIT, the program runs. You take other events (key, mouse) meanwhile with PollEvent.
sdl.PushQuitEvent
sdl.PushQuitEvent() -> int
Programmatically pushes a QUIT event into the SDL2 queue.
This function takes no arguments.
1 on success.
sdl.PushQuitEvent(); // the next PollQuit will return 11
For triggering exit from the script's own code (for example on a button press): the next PollQuit gives 1 and the main loop stops. Cleaner than closing the window from outside.
sdl.EventKeyCode
sdl.EventKeyCode() -> int
The last keyboard event's key code.
This function takes no arguments.
The key code (or 0 if there has been no keyboard event yet).
printf("%d\n", sdl.EventKeyCode());0
After PollEvent, if a KEYDOWN/KEYUP-type event arrived: it gives the pressed (or released) key code. The KeyCode function gives you a comparison code by name.
sdl.EventMouseX
sdl.EventMouseX() -> int
The X coordinate of the last mouse event.
This function takes no arguments.
The X value (or 0 if there has been no mouse event yet).
printf("%d\n", sdl.EventMouseX());0
After MOUSEMOTION/MOUSEBUTTONDOWN/UP: the X coordinate of the mouse position. EventMouseY gives its counterpart.
sdl.EventMouseY
sdl.EventMouseY() -> int
The Y coordinate of the last mouse event.
This function takes no arguments.
The Y value (or 0 if there has been no mouse event yet).
printf("%d\n", sdl.EventMouseY());0
The counterpart of EventMouseX: together they give the exact mouse position.
sdl.EventMouseButton
sdl.EventMouseButton() -> int
The button identifier of the last mouse button event.
This function takes no arguments.
The button identifier (1=left, 2=middle, 3=right), or 0 if there has been no such event.
printf("%d\n", sdl.EventMouseButton());0
After MOUSEBUTTONDOWN/UP: which button was clicked. Comparable with the MouseLeftButton/Middle/Right constants.
sdl.EventWheelX
sdl.EventWheelX() -> int
The horizontal (X-direction) value of the last wheel event.
This function takes no arguments.
The wheel X direction (positive or negative), or 0.
printf("%d\n", sdl.EventWheelX());0
For tracking horizontal scrolling or sideways button movement (rare, but some mice support it).
sdl.EventWheelY
sdl.EventWheelY() -> int
The vertical (Y-direction) value of the last wheel event.
This function takes no arguments.
The wheel Y direction (positive=forward, negative=back), or 0.
printf("%d\n", sdl.EventWheelY());0
For tracking the most common mouse wheel scrolling (vertical) — for zoom, scrolling, list selection.
Event handling (asynchronous callback)
You register a script-level callback function that SDL2's background thread invokes for every event. The main thread's state is shown by the probes (Active/Delivered/Dropped/HasReply).
sdl.SetEventCallback
sdl.SetEventCallback(callback, timeoutMs) -> int
Sets a script-level callback to be invoked for every incoming event (with an event blob).
| Parameter | Type | Description |
|---|---|---|
| callback | string | The name of the script function to call (it takes an event blob and may give a reply). |
| timeoutMs | int | The wait timeout in milliseconds for the callback's reply. |
1 on success.
sdl.SetEventCallback("onEvent", 50);
// i32 onEvent(blob $packet) { ... return(0); }(the callback runs for every event)
For event-driven programming: the background thread automatically notifies you of every event. More convenient than the PollEvent loop if event processing is costly or needs asynchronous logic.
sdl.ClearEventCallback
sdl.ClearEventCallback() -> int
Removes the configured event callback.
This function takes no arguments.
1 on success.
sdl.ClearEventCallback();
1
When you want to switch from the callback pattern to the synchronous Poll* pattern, or end event handling.
sdl.EventCallbackActive
sdl.EventCallbackActive() -> int
Tells whether there is an active event callback.
This function takes no arguments.
1 if there is; otherwise 0.
printf("%d\n", sdl.EventCallbackActive());0
For a check: whether a callback is enabled, before registering another or turning off the existing one.
sdl.EventCallbackDelivered
sdl.EventCallbackDelivered() -> int
Returns how many events the background thread has delivered to the callback so far.
This function takes no arguments.
The number of delivered events.
printf("%d\n", sdl.EventCallbackDelivered());0
For diagnostics: you can watch how many events the callback has actually processed (since the start of the run).
sdl.EventCallbackDropped
sdl.EventCallbackDropped() -> int
Returns how many events the background thread has dropped (because the callback did not finish in time).
This function takes no arguments.
The number of dropped events.
printf("%d\n", sdl.EventCallbackDropped());0
For performance monitoring: if there are frequent drops, the callback is slower than the configured timeoutMs. You can raise timeoutMs or rewrite the callback to be faster.
sdl.HasEventCallbackReply
sdl.HasEventCallbackReply() -> int
Tells whether there is a pending reply (reply blob) from the callback.
This function takes no arguments.
1 if there is; otherwise 0.
if (sdl.HasEventCallbackReply() == 1) { /* take */ }0
Before calling TakeEventCallbackReply: you check whether there is something to take. The callback can reply to the event, which the main thread takes this way.
sdl.TakeEventCallbackReply
sdl.TakeEventCallbackReply() -> blob
Takes a pending callback reply into the main thread.
This function takes no arguments.
The reply blob (empty if there is none).
blob $reply[256];
if (sdl.HasEventCallbackReply() == 1) { $reply =
sdl.TakeEventCallbackReply(); }(the callback's reply)
For taking data sent from the async callback to the main thread. The callback can dictate, at script level, what blob it replies with — for example sending the pressed key back to the main thread for its own processing.
Input (constants)
Key name → key code conversion, and the constants of the mouse buttons. These verbs do not require SDL2 initialization — they can be safely run.
sdl.KeyCode
sdl.KeyCode(name) -> int
Converts a key name (or a single character) into a key code.
| Parameter | Type | Description |
|---|---|---|
| name | string | The key name: a single 0-9/a-z character, or one of these names: Return, Enter, Escape, Space, Tab, Backspace, Left, Right, Up, Down (case-insensitive). |
The key code. An unknown name causes a runtime error.
printf("%d\n", sdl.KeyCode("Return"));
printf("%d\n", sdl.KeyCode("a"));13 97
For key comparison: you can compare the value returned by EventKeyCode after PollEvent with this. Letters are normalized to lowercase (KeyCode("A") == KeyCode("a") == 97).
sdl.MouseLeftButton
sdl.MouseLeftButton() -> int
Returns the identifier of the left mouse button (a constant).
This function takes no arguments.
1.
printf("%d\n", sdl.MouseLeftButton());1
For a more readable comparison of the value returned by EventMouseButton: if (sdl.EventMouseButton() == sdl.MouseLeftButton()).
sdl.MouseMiddleButton
sdl.MouseMiddleButton() -> int
Returns the identifier of the middle mouse button (a constant).
This function takes no arguments.
2.
printf("%d\n", sdl.MouseMiddleButton());2
For recognizing a click with the wheel button (usually pressing the wheel).
sdl.MouseRightButton
sdl.MouseRightButton() -> int
Returns the identifier of the right mouse button (a constant).
This function takes no arguments.
3.
printf("%d\n", sdl.MouseRightButton());3
For recognizing a local (context) menu or a secondary action.
Audio
Opening an audio device, loading and playing WAV files, and a synthesized tone.
sdl.OpenAudio
sdl.OpenAudio(sampleRate) -> int
Opens an audio device with the given sample rate (and returns an audio handle).
| Parameter | Type | Description |
|---|---|---|
| sampleRate | int | The sample rate in hertz (typically 44100 or 48000). |
The audio handle (a positive integer). A failed opening or a missing audio device causes a runtime error.
i32 $audio;
$audio = sdl.OpenAudio(44100);
// ... LoadWav + PlayWav or PlayTone ...
sdl.CloseAudio($audio);(the audio handle by which you play sound)
The first step of sound playback. If the audio device is not available (for example in a server environment), TryOpenAudio is the failure-free alternative.
sdl.TryOpenAudio
sdl.TryOpenAudio(sampleRate) -> int
Tries to open an audio device, but with a missing device it does not fail — it returns 0.
| Parameter | Type | Description |
|---|---|---|
| sampleRate | int | The sample rate in hertz. |
The audio handle if it succeeded; 0 if the device is not available.
i32 $audio;
$audio = sdl.TryOpenAudio(44100);
if ($audio > 0) { /* have sound */ }(handle or 0)
For optional sound support: if audio is available, use it; if not, the program continues silently. Excellent in a server or headless environment.
sdl.CloseAudio
sdl.CloseAudio(audioId) -> int
Closes the audio device and releases its resources.
| Parameter | Type | Description |
|---|---|---|
| audioId | int | The audio handle. |
1 on success.
sdl.CloseAudio($audio);
1
At the end of audio use — releases the device for other applications. Close the WAVs loaded with LoadWav separately first.
sdl.StopAudio
sdl.StopAudio(audioId) -> int
Stops the currently playing sound on the given audio device.
| Parameter | Type | Description |
|---|---|---|
| audioId | int | The audio handle. |
1 on success.
sdl.StopAudio($audio);
1
If you want to play another sound, or playback must stop on user request. The audio device stays open; only the active sound is cut off.
sdl.LoadWav
sdl.LoadWav(audioId, path) -> int
Loads a WAV file for the given audio device, and returns a WAV handle.
| Parameter | Type | Description |
|---|---|---|
| audioId | int | The target audio handle. |
| path | string | The WAV file path. |
The WAV handle (a positive integer). A missing file or a wrong format causes a runtime error.
i32 $wav; $wav = sdl.LoadWav($audio, "sounds/click.wav");
(the WAV handle by which you play the sound)
For loading sound effects. A loaded WAV can be played multiple times with PlayWav; free it with CloseWav at the end.
sdl.CloseWav
sdl.CloseWav(wavId) -> int
Releases the memory of a loaded WAV file.
| Parameter | Type | Description |
|---|---|---|
| wavId | int | The WAV handle. |
1 on success.
sdl.CloseWav($wav);
1
Close every WAV belonging to a LoadWav when no longer needed — otherwise memory can pile up.
sdl.PlayWav
sdl.PlayWav(wavId, repeatCount, volumePercent) -> int
Plays a loaded WAV with the given repeat count and volume percent.
| Parameter | Type | Description |
|---|---|---|
| wavId | int | The WAV handle. |
| repeatCount | int | How many times to play (0 = once; -1 = infinite). |
| volumePercent | int | The volume between 0..100. |
1 on success.
sdl.PlayWav($wav, 0, 80); // once, at 80% volume(the WAV is heard)
For sound effects (click, collision, notification). For longer background music, use infinite repeat (-1), and stop it with StopAudio when needed.
sdl.PlayTone
sdl.PlayTone(audioId, frequencyHz, durationMs, volumePercent) -> int
Plays a simple sine tone at the given frequency, duration, and volume.
| Parameter | Type | Description |
|---|---|---|
| audioId | int | The audio handle. |
| frequencyHz | int | The tone frequency in hertz (e.g. 440 = A4). |
| durationMs | int | The tone duration in milliseconds. |
| volumePercent | int | The volume between 0..100. |
1 on success.
sdl.PlayTone($audio, 440, 500, 70); // A4, 500 ms, 70%(a half-second A4 tone)
For feedback sounds (beep, bell, chirp), or for simple melodic signals without a WAV file. By chaining several tones in time, a tune can also be made.
Textures
Loading images as textures (BMP, and with SDL2_image present PNG/JPG/WebP), drawing textures on the window, resizing, rotating, and transparency.
sdl.LoadTexture
sdl.LoadTexture(windowId, path) -> int
Loads an image as a texture for the given window; returns a texture handle.
| Parameter | Type | Description |
|---|---|---|
| windowId | int | The window handle the texture belongs to. |
| path | string | The image path (BMP always; PNG/JPG/WebP only with SDL2_image present). |
The texture handle (a positive integer). On error, a runtime error.
i32 $tex; $tex = sdl.LoadTexture($win, "sprite.png");
(the texture handle)
For loading sprites, icons, backgrounds. If you want to use PNG/JPG/WebP files, check first with the Image*Supported functions whether SDL2_image is available.
sdl.CloseTexture
sdl.CloseTexture(textureId) -> int
Releases the memory of a texture.
| Parameter | Type | Description |
|---|---|---|
| textureId | int | The texture handle. |
1 on success.
sdl.CloseTexture($tex);
1
Close every loaded texture when no longer needed. Before the window's CloseWindow, close all the textures belonging to it.
sdl.TextureWidth
sdl.TextureWidth(textureId) -> int
Returns the texture width in pixels.
| Parameter | Type | Description |
|---|---|---|
| textureId | int | The texture handle. |
The width in pixels.
printf("%d\n", sdl.TextureWidth($tex));(the texture width)
To query the loaded image's actual size — for example so you can center it or rescale it to a given size.
sdl.TextureHeight
sdl.TextureHeight(textureId) -> int
Returns the texture height in pixels.
| Parameter | Type | Description |
|---|---|---|
| textureId | int | The texture handle. |
The height in pixels.
printf("%d\n", sdl.TextureHeight($tex));(the texture height)
The counterpart of TextureWidth: together they give the texture's actual size.
sdl.DrawTexture
sdl.DrawTexture(textureId, x, y) -> int
Draws the texture on the window at the given position, at its original size.
| Parameter | Type | Description |
|---|---|---|
| textureId | int | The texture handle. |
| x | int | The target upper-left corner's X coordinate. |
| y | int | The target upper-left corner's Y coordinate. |
1 on success.
sdl.DrawTexture($tex, 100, 50);
(the texture appears at the given place)
The most common texture drawing: places it at the original size. If you need another size, DrawTextureRect; for rotation/flip, DrawTextureEx.
sdl.DrawTextureRect
sdl.DrawTextureRect(textureId, x, y, width, height) -> int
Draws the texture at the given position and size (scaled).
| Parameter | Type | Description |
|---|---|---|
| textureId | int | The texture handle. |
| x | int | The target X coordinate. |
| y | int | The target Y coordinate. |
| width | int | The target width. |
| height | int | The target height. |
1 on success.
sdl.DrawTextureRect($tex, 50, 50, 200, 100);
(the texture is stretched to 200×100)
For drawing that requires a size change: enlarging an icon, using an image as a filled background, or resizing a UI element.
sdl.SetTextureColor
sdl.SetTextureColor(textureId, r, g, b) -> int
Sets the texture's color modulator (multiplies the displayed colors).
| Parameter | Type | Description |
|---|---|---|
| textureId | int | The texture handle. |
| r | int | Red modulator (0..255; 255 = unchanged). |
| g | int | Green modulator (0..255). |
| b | int | Blue modulator (0..255). |
1 on success.
sdl.SetTextureColor($tex, 128, 255, 128); // greenish tint(the texture takes a greenish tint)
For color effects on a texture (red flash on damage, dampened color with a gray shade). The values multiply the texture's original colors: 255 = unchanged, 128 = half intensity.
sdl.SetTextureAlpha
sdl.SetTextureAlpha(textureId, alpha) -> int
Sets the texture's transparency (alpha multiplier).
| Parameter | Type | Description |
|---|---|---|
| textureId | int | The texture handle. |
| alpha | int | The alpha value 0..255 (0 = fully transparent, 255 = opaque). |
1 on success.
sdl.SetTextureAlpha($tex, 128); // half transparent(the texture becomes half transparent)
For fade-in/fade-out animations, or transparent UI elements (for example a panel that half-covers the background).
sdl.DrawTexturePart
sdl.DrawTexturePart(textureId, srcX, srcY, srcWidth, srcHeight, dstX, dstY, dstWidth, dstHeight) -> int
Draws a rectangular slice of the texture onto a rectangular slice of the window (source → destination mapping).
| Parameter | Type | Description |
|---|---|---|
| textureId | int | The texture handle. |
| srcX | int | The source rectangle's X on the texture. |
| srcY | int | The source rectangle's Y on the texture. |
| srcWidth | int | The source rectangle width. |
| srcHeight | int | The source rectangle height. |
| dstX | int | The target X on the window. |
| dstY | int | The target Y on the window. |
| dstWidth | int | The target width (scaling possible). |
| dstHeight | int | The target height (scaling possible). |
1 on success.
// drawing the 2nd cell (32..63, 0..31) from a 32x32 sprite sheet
sdl.DrawTexturePart($sheet, 32, 0, 32, 32, 100, 100, 32, 32);(a piece of the sprite sheet is visible)
For sprite sheets: cutting a given character, tile, or animation frame from a large image. The source and destination rectangles are independent, so scaling is also possible at the same time.
sdl.DrawTextureEx
sdl.DrawTextureEx(textureId, x, y, width, height, angleDeg, flipX, flipY) -> int
Draws the texture rotated and/or flipped, at the given position and size.
| Parameter | Type | Description |
|---|---|---|
| textureId | int | The texture handle. |
| x | int | The target X coordinate. |
| y | int | The target Y coordinate. |
| width | int | The target width. |
| height | int | The target height. |
| angleDeg | int | Rotation angle in degrees (around the center). |
| flipX | int | Horizontal flip (0 or 1). |
| flipY | int | Vertical flip (0 or 1). |
1 on success.
sdl.DrawTextureEx($tex, 100, 100, 64, 64, 45, 0, 0); // rotated by 45
degrees(the texture appears rotated)
For a rotating or flipped sprite (for example a character that looks right or left with flipX). The rotation happens around the rectangle's center.
sdl.ImageRuntimeLoaded
sdl.ImageRuntimeLoaded() -> int
Tells whether the SDL2_image library has been loaded (i.e. PNG/JPG/WebP support is available).
This function takes no arguments.
1 if SDL2_image is available; otherwise 0.
printf("%d\n", sdl.ImageRuntimeLoaded());0
For checks before PNG/JPG/WebP texture loading. If 0, you can only load BMP files with LoadTexture.
sdl.ImagePngSupported
sdl.ImagePngSupported() -> int
Tells whether the PNG format can be loaded (through SDL2_image).
This function takes no arguments.
1 if supported; otherwise 0.
printf("%d\n", sdl.ImagePngSupported());0
Worth checking before using PNG files — otherwise LoadTexture can fail. SDL2_image is mostly installed for PNG support.
sdl.ImageJpgSupported
sdl.ImageJpgSupported() -> int
Tells whether the JPG format can be loaded.
This function takes no arguments.
1 if supported; otherwise 0.
printf("%d\n", sdl.ImageJpgSupported());0
For a check before using JPG files. JPG is less universal than PNG through SDL2_image.
sdl.ImageWebpSupported
sdl.ImageWebpSupported() -> int
Tells whether the WebP format can be loaded.
This function takes no arguments.
1 if supported; otherwise 0.
printf("%d\n", sdl.ImageWebpSupported());0
For a check before using WebP files. WebP is the most often missing support, since not every SDL2_image build contains it.
Practical notes
What the sdl plugin is good for
Making 2D games and visual demonstrations: window, sprites, animation, input, audio.
Graphical extension of interactive command-line tools: visual feedback, state display, button control.
Multimedia scripts: playing back sound samples and tones, WAV-file mixing.
Simple image display and sprite graphics: loading textures (from BMP always, from PNG/JPG/WebP with SDL2_image), drawing, sizing, rotation, flipping.
Lifecycle
The typical order: Init → OpenWindow → (perhaps OpenAudio + LoadWav, LoadTexture) → main loop (PollEvent + Clear/FillRect/DrawTexture* + Present) → resource closing (CloseWav, CloseTexture, CloseAudio) → CloseWindow → Quit. Every Open*/Load* has a matching Close* — call them in reverse order.
Synchronous vs asynchronous event handling
Two styles are available. The SYNCHRONOUS pattern (PollEvent + Event*) is simple and easy to understand: the main thread asks for events on every frame and reacts to them. The ASYNCHRONOUS pattern (SetEventCallback) works with a background thread that automatically notifies you of every event — more convenient if events are rare or processing requires async logic. The Delivered/Dropped probes help diagnose the callback's performance.
Relationship to the opengl plugin
The sdl and opengl plugins can be used in parallel INDEPENDENTLY of each other, but they have their own windows and state. sdl is for 2D drawing (rectangles, lines, textures), 2D sprites, audio, and event handling. opengl provides a high-level 3D scene and OpenGL fixed-pipeline wrappers. A script usually picks one; if you need 3D, use opengl; if 2D and multimedia, use sdl.
Image format support
BMP files are always loaded by the SDL2 base API. Loading PNG/JPG/WebP requires the SDL2_image library at runtime — ImageRuntimeLoaded and Image*Supported report its presence. If SDL2_image is missing, you can only work with BMP, or arrange for it to be installed.
Error handling
A wrong argument count or type, an invalid handle, a failed SDL2 load, and a bad file path are reported by the runtime as a runtime error, and the script stops. The usual states are signaled by a neutral return value: PollEvent and PollQuit give 0 if there is no event; Image*Supported gives 0/1; the Event* getters give 0 if there has been no event yet. For fault-tolerant audio opening there is TryOpenAudio (gives 0 for a missing device); Init/Quit/Close*/Stop*, which return 1 on success, can all be used safely.
The asyncmeta async-constants-catalog plugin
Phase, status, capability, and field constants for the async callback plugins — complete function reference