### Send HTTP Requests (GET, POST, Query) Source: https://sdk.play.date/3.0.1/Inside%20Playdate%20with%20C Functions to send HTTP requests. `get` sends a GET request, while `post` is a convenience for sending POST requests. `query` allows for custom HTTP methods and request bodies. These functions initiate the connection if not already open and transmit the request data. ```c PDNetErr playdate->network->http->get(HTTPConnection* conn, const char* path, const char* headers, size_t headerlen); PDNetErr playdate->network->http->query(HTTPConnection* conn, const char* method, const char* path, const char* headers, size_t headerlen, const char* body, size_t bodylen); PDNetErr playdate->network->http->post(HTTPConnection* conn, const char* path, const char* headers, size_t headerlen, const char* body, size_t bodylen); ``` -------------------------------- ### Accelerometer Ball Rolling Demo (Lua) Source: https://sdk.play.date/3.0.1/Inside%20Playdate A complete example demonstrating how to use the accelerometer to control a ball's movement on the screen. It includes starting the accelerometer, reading its values, clamping movement, and drawing the ball in the update loop. ```lua import "CoreLibs/graphics" local function clamp(value, min, max) return math.max(math.min(value, max), min) end local x, y = 200, 120 -- Make sure to start the accelerometer to begin reading! playdate.startAccelerometer() -- A simple example of rolling around a ball on the screen using the accelerometer function playdate.update() playdate.graphics.clear() -- We can get the accelerometer values by storing them in multiple variables local gravityX, gravityY, _gravityZ = playdate.readAccelerometer() -- Try orienting the Playdate flat and tilting it around x = clamp(x + gravityX * 10, 0, 400) y = clamp(y + gravityY * 10, 0, 240) playdate.graphics.fillCircleAtPoint(x, y, 10) end ``` -------------------------------- ### Making HTTP Requests Source: https://sdk.play.date/3.0.1/Inside%20Playdate Methods for sending GET, query, and POST requests and handling the connection and data. ```APIDOC ## Making HTTP Requests ### Description These methods are used to initiate and send HTTP requests to a server. ### Methods #### `playdate.network.http:get(path, [headers])` ##### Description Opens the connection to the server if it’s not already open and sends a GET request for the specified path. Additional headers can be provided. ##### Parameters * **path** (string) - Required - The path to request on the server. * **headers** (string | table | table) - Optional - Additional headers to send with the request. Can be a string, an array of strings, or a table of key/value pairs. ##### Returns * `boolean` - `true` if the request was successfully queued, `false` on error. * `string` - An error message if the request failed. #### `playdate.network.http:query(path, [headers], data)` ##### Description Opens the connection to the server if it’s not already open and sends a request with the specified path, headers, and data. This is a general-purpose request method. ##### Parameters * **path** (string) - Required - The path to request on the server. * **headers** (string | table | table) - Optional - Additional headers to send with the request. * **data** (any) - Required - The data to send with the request. If only one argument follows `path`, it is assumed to be `data`. ##### Returns * `boolean` - `true` if the request was successfully queued, `false` on error. * `string` - An error message if the request failed. #### `playdate.network.http:post(path, [headers], data)` ##### Description Equivalent to calling `playdate.network.http:query()` with the method set to `POST`. ##### Parameters * **path** (string) - Required - The path to request on the server. * **headers** (string | table | table) - Optional - Additional headers to send with the request. * **data** (any) - Required - The data to send with the request. ##### Returns * `boolean` - `true` if the request was successfully queued, `false` on error. * `string` - An error message if the request failed. ``` -------------------------------- ### playdate.sound.sampleplayer:play Source: https://sdk.play.date/3.0.1/Inside%20Playdate Starts playing the loaded sample with optional repeat count and playback rate. ```APIDOC ## playdate.sound.sampleplayer:play ### Description Starts playing the loaded sample with optional repeat count and playback rate. ### Method N/A (Method) ### Endpoint N/A (Method) ### Parameters #### Query Parameters - **repeatCount** (number) - Optional - Number of times to loop the sample (0 for endless). - **rate** (number) - Optional - Playback rate (overrides previously set rate). ### Response - No return value. ``` -------------------------------- ### Building for Simulator using NMake Source: https://sdk.play.date/3.0.1/Inside%20Playdate%20with%20C Instructions on building the Playdate game for the simulator using NMake. This involves navigating to the project directory, creating a build folder, and using CMake and NMake commands. ```NMake cmake .. -G "NMake Makefiles" ``` ```NMake nmake ``` -------------------------------- ### GET – Send HTTP GET Request Source: https://sdk.play.date/3.0.1/Inside%20Playdate%20with%20C Sends a GET request over an existing HTTPConnection and retrieves the response. ```APIDOC ## GET (C Function)\n\n### Description\nOpens the connection if needed and sends an HTTP GET request to the specified path with optional headers.\n\n### Method\nGET\n\n### Endpoint\nplaynetwork->http->get(HTTPConnection* conn, const char* path, const char* headers, size_t headerlen)\n\n### Parameters\n#### Path Parameters\n- **conn** (HTTPConnection*) - Required - The connection object to use.\n- **path** (const char*) - Required - Request path (e.g., "/v1/data").\n\n#### Query Parameters\n- **headers** (const char*) - Optional - Additional HTTP header lines separated by "\r\n".\n- **headerlen** (size_t) - Optional - Length of the headers string.\n\n#### Request Body\nNone\n\n### Request Example\n{\n "path": "/api/status",\n "headers": "Accept: application/json\r\nUser-Agent: PlaydateSDK/3.0"\n}\n\n### Response\n#### Success Response (PDNetErr)\n- **errorCode** (PDNetErr) - NET_OK if request succeeded.\n\n#### Additional Data\n- Use getResponseStatus, getBytesAvailable, read, etc., to retrieve payload.\n\n### Response Example\n{\n "errorCode": "NET_OK",\n "status": ,\n "body": "{\"online\":true}"\n} ``` -------------------------------- ### Playdate TCP Connection Setup and Management Source: https://sdk.play.date/3.0.1/Inside%20Playdate Demonstrates how to establish and manage TCP connections in Playdate SDK. Shows connection opening with callback handling, error checking, and connection status reporting. Requires playdate.network.tcp module and appropriate network permissions. ```lua connection:open(function tcpConnectCallback(connected, err) if connected then print("connected!") else print("connection failed: "..err) end end) ``` -------------------------------- ### Get Crank Ticks Revolution (Lua) Source: https://sdk.play.date/3.0.1/Inside%20Playdate Counts tick boundaries based on specified revolutions. Requires importing CoreLibs/crank library. Returns number of ticks passed since last call, with positive values for forward rotation and negative for backward. Tick boundaries are set at absolute positions. Example shows 6 ticks per revolution (60-degree increments). ```Lua import "CoreLibs/crank" local ticksPerRevolution = 6 function playdate.update() local crankTicks = playdate.getCrankTicks(ticksPerRevolution) if crankTicks == 1 then print("Forward tick") elseif crankTicks == -1 then print("Backward tick") end end ``` -------------------------------- ### Building for Device using NMake Source: https://sdk.play.date/3.0.1/Inside%20Playdate%20with%20C Instructions on building the Playdate game for the device using NMake and the ARM toolchain. Similar to simulator build, but with the `--toolchain` argument to specify the ARM toolchain. ```NMake cmake .. -G "NMake Makefiles" --toolchain=/C_API/buildsupport/arm.cmake ``` ```NMake nmake ``` -------------------------------- ### Create Standalone Sprite in Lua Source: https://sdk.play.date/3.0.1/Inside%20Playdate This example demonstrates creating a basic sprite object from an image file using the Playdate SDK's sprite API. It requires the 'CoreLibs/sprites' library to be imported. The sprite is positioned at coordinates (100, 100) and added to the display list, with no user inputs beyond initial setup. Limitations include basic functionality without subclassing for advanced behaviors. ```lua import "CoreLibs/sprites" local image = playdate.graphics.image.new("coin") local sprite = playdate.graphics.sprite.new(image) sprite:moveTo(100, 100) sprite:add() ``` -------------------------------- ### Basic Playdate Game in Lua Source: https://sdk.play.date/3.0.1/Inside%20Playdate Demonstrates the fundamental structure of a Playdate game written in Lua. It includes a minimal example of game initialization and the main update loop, showing how to handle game logic and rendering. ```lua function init() -- Game initialization code here playdate.display.setRefreshRate(60) end function update(event) if event == playdate.update THEN -- Game logic and drawing code here playdate.graphics.clear(playdate.graphics.kColorBlack) playdate.graphics.setColor(playdate.graphics.kColorWhite) playdate.graphics.drawText("Hello, Playdate!", 100, 120) end end -- Call init() when the script is loaded init() -- The update function will be called by the system -- No need to explicitly call update() here unless for specific testing scenarios ``` -------------------------------- ### Creating Value Transition Timer in Lua Source: https://sdk.play.date/3.0.1/Inside%20Playdate This example shows creating a frameTimer to interpolate between start and end values over frames, using linear easing by default. Access the interpolated value via the value property during runtime. The timer auto-discards on completion; suitable for smooth UI or animation transitions. Requires Playdate SDK; inputs are duration, startValue, endValue; outputs current value; limited to frame-based timing. ```lua t = FrameTimer(50, 0, 100) ``` -------------------------------- ### Audio Sample Creation and Loading (C) Source: https://sdk.play.date/3.0.1/Inside%20Playdate%20with%20C Functions for creating and loading audio samples. `newSampleBuffer` allocates memory for a sample, `loadIntoSample` loads data into an existing sample, and `load` allocates and loads a sample from a file path. Returns null if the file is not found. ```c AudioSample* playdate->sound->sample->newSampleBuffer(int length); void playdate->sound->sample->loadIntoSample(AudioSample* sample, const char* path); AudioSample* playdate->sound->sample->load(const char* path); ``` -------------------------------- ### Playdate Lua: Get Argument Types and Count (C) Source: https://sdk.play.date/3.0.1/Inside%20Playdate%20with%20C Functions to retrieve information about arguments passed from Lua to a C function. Includes getting the type of an argument at a specific position, retrieving the name of an object's metatable, and getting the total number of arguments. ```c enum LuaType playdate->lua->getArgType(int pos, const char** outClass); int playdate->lua->getArgCount(void); ``` -------------------------------- ### Build Device Binary Using CMake and Make Source: https://sdk.play.date/3.0.1/Inside%20Playdate%20with%20C Configures CMake with the ARM toolchain for cross-compiling a device binary, then builds it with Make and integrates into the .pdx bundle. Delete or use a separate build folder to avoid Simulator conflicts. Requires PLAYDATE_SDK_PATH set and ARM compiler installed. ```bash cd build cmake -DCMAKE_TOOLCHAIN_FILE=/C_API/buildsupport/arm.cmake .. make ``` -------------------------------- ### Recommended Playdate Project Directory Structure Source: https://sdk.play.date/3.0.1/Inside%20Playdate Standard directory layout for Playdate projects with source folder containing main.lua, additional Lua files, images subfolder for PNG files, and sounds subfolder for audio files. Also includes support folder for project assets. Forward slashes must be used for cross-platform compatibility. ```Text [myProjectName]/ source/ main.lua ...and other .lua files images/ [myImageFile1].png [myImageFile2].png ...and so on sounds/ [myAudioFile1].wav [myAudioFile2].mp3 ...and other ADPCM- or MP3-formatted files support/ Project files including Photoshop assets, project outlines, etc. ``` -------------------------------- ### Sample pdxinfo File Configuration Source: https://sdk.play.date/3.0.1/Inside%20Playdate A sample _pdxinfo_ file used to define game metadata such as name, author, description, bundle ID, version, build number, and asset paths. This file is placed at the root of the project and its contents are accessible via `playdate.metadata`. ```ini name=b360 author=Panic Inc. description=When all you have is a ton of bricks, everything looks like a paddle. bundleID=com.panic.b360 version=1.0 buildNumber=123 imagePath=path/to/launcher/assets launchSoundPath=path/to/launch/sound/file contentWarning=This game contains mild realistic violence and bloodshed. contentWarning2=This game contains flashing content that may not be suitable for photosensitive epilepsy. ``` -------------------------------- ### Accelerometer Control and Reading (Lua) Source: https://sdk.play.date/3.0.1/Inside%20Playdate Functions to start, stop, read, and check the status of the device's accelerometer. Reading requires starting it first. Returns x, y, and z values as a list. ```lua playdate.startAccelerometer() local accelValues = playdate.readAccelerometer() playdate.stopAccelerometer() local isRunning = playdate.accelerometerIsRunning() ``` -------------------------------- ### Get Menu Item Title and Set/Get Value (Lua) Source: https://sdk.play.date/3.0.1/Inside%20Playdate Provides functions to retrieve a menu item's title and to set or get its value. The type of the value depends on the menu item type (normal, checkmark, options). Values can also be set using dot syntax. ```lua local currentTitle = playdate.menu.item:getTitle() playdate.menu.item:setValue(newValue) -- or using dot syntax: -- playdate.menu.item.value = newValue local currentValue = playdate.menu.item:getValue() ``` -------------------------------- ### Using the Simulator in Playdate Source: https://sdk.play.date/3.0.1/Inside%20Playdate Explains how to use the Playdate Simulator for development and testing. It covers running games, controlling the simulator with the physical device, and debugging tools. ```shell # To run the simulator from the command line: # Navigate to your project directory and run: playdate-simulator --device "Your Project Name" ``` -------------------------------- ### JSON Reader Structure and File Example (C) Source: https://sdk.play.date/3.0.1/Inside%20Playdate%20with%20C The json_reader struct provides a read callback for supplying data to the decoder, with userdata for context like file handles. The example reads from a file using Playdate's file API; inputs are buffer and size, outputs bytes read or 0 on EOF. Depends on pd->file; limitation: Binary-safe but assumes UTF-8 JSON. ```C typedef struct { int (*read)(void* readud, uint8_t* buf, int bufsize); // fill buffer, return bytes written or 0 on end of data void* userdata; } json_reader; ``` ```C int readfile(void* readud, uint8_t* buf, int bufsize) { return playdate->file->read((SDFile*)readud, buf, bufsize); } ``` ```C SDFile* file = pd->file->open("data.json", kFileRead); pd->json->decode(&decoder, (json_reader){ .read = readfile, .userdata = file }, NULL); ``` -------------------------------- ### Basic Playdate Game Setup and Update in Lua Source: https://sdk.play.date/3.0.1/Inside%20Playdate This Lua code initializes a Playdate game by setting up a player sprite and a background image. It then defines the `playdate.update()` function to handle player movement based on d-pad input and updates game elements like sprites and timers. The code relies on Playdate's CoreLibs for graphics and sprites. ```lua -- Name this file `main.lua`. Your game can use multiple source files if you wish -- (use the `import "myFilename"` command), but the simplest games can be written -- with just `main.lua`. -- You'll want to import these in just about every project you'll work on. import "CoreLibs/object" import "CoreLibs/graphics" import "CoreLibs/sprites" import "CoreLibs/timer" -- Declaring this "gfx" shorthand will make your life easier. Instead of having -- to preface all graphics calls with "playdate.graphics", just use "gfx." -- Performance will be slightly enhanced, too. -- NOTE: Because it's local, you'll have to do it in every .lua source file. local gfx = playdate.graphics -- Here's our player sprite declaration. We'll scope it to this file because -- several functions need to access it. local playerSprite = nil -- A function to set up our game environment. function myGameSetUp() -- Set up the player sprite. local playerImage = gfx.image.new("Images/playerImage") assert( playerImage ) -- make sure the image was where we thought playerSprite = gfx.sprite.new( playerImage ) playerSprite:moveTo( 200, 120 ) -- this is where the center of the sprite is placed; (200,120) is the center of the Playdate screen playerSprite:add() -- This is critical! -- We want an environment displayed behind our sprite. -- There are generally two ways to do this: -- 1) Use setBackgroundDrawingCallback() to draw a background image. (This is what we're doing below.) -- 2) Use a tilemap, assign it to a sprite with sprite:setTilemap(tilemap), -- and call :setZIndex() with some low number so the background stays behind -- your other sprites. local backgroundImage = gfx.image.new( "Images/background" ) assert( backgroundImage ) gfx.sprite.setBackgroundDrawingCallback( function( x, y, width, height ) -- x,y,width,height is the updated area in sprite-local coordinates -- The clip rect is already set to this area, so we don't need to set it ourselves backgroundImage:draw( 0, 0 ) end ) end -- Now we'll call the function above to configure our game. -- After this runs (it just runs once), nearly everything will be -- controlled by the OS calling `playdate.update()` 30 times a second. myGameSetUp() -- `playdate.update()` is the heart of every Playdate game. -- This function is called right before every frame is drawn onscreen. -- Use this function to poll input, run game logic, and move sprites. function playdate.update() -- Poll the d-pad and move our player accordingly. -- (There are multiple ways to read the d-pad; this is the simplest.) -- Note that it is possible for more than one of these directions -- to be pressed at once, if the user is pressing diagonally. if playdate.buttonIsPressed( playdate.kButtonUp ) then playerSprite:moveBy( 0, -2 ) end if playdate.buttonIsPressed( playdate.kButtonRight ) then playerSprite:moveBy( 2, 0 ) end if playdate.buttonIsPressed( playdate.kButtonDown ) then playerSprite:moveBy( 0, 2 ) end if playdate.buttonIsPressed( playdate.kButtonLeft ) then playerSprite:moveBy( -2, 0 ) end -- Call the functions below in playdate.update() to draw sprites and keep -- timers updated. (We aren't using timers in this example, but in most -- average-complexity games, you will.) gfx.sprite.update() playdate.timer.updateTimers() end ``` -------------------------------- ### Get file type - Playdate SDK Source: https://sdk.play.date/3.0.1/Inside%20Playdate Returns the type of the file at the specified path. ```Lua playdate.file.getType(path) ``` -------------------------------- ### Game Control and Information Source: https://sdk.play.date/3.0.1/Inside%20Playdate%20with%20C Restart the game, retrieve launch arguments, and set serial message callbacks. ```APIDOC ## POST /system/restart ### Description Reinitializes the Playdate runtime and restarts the currently running game. The `args` string is available after restart via `getLaunchArgs()`. ### Method POST ### Endpoint /system/restart ### Parameters #### Request Body - **args** (string) - Optional arguments to pass to the restarted game. ### Request Example ```json { "args": "--newgame" } ``` ### Response #### Success Response (200) No content. ## GET /system/getLaunchArgs ### Description Returns the string passed as an argument at launch time. Optionally returns the path of the currently loaded game. ### Method GET ### Endpoint /system/getLaunchArgs ### Parameters None ### Request Example None ### Response #### Success Response (200) - **launchArgs** (string) - The launch arguments string. - **outpath** (string) - The path of the currently loaded game (if `outpath` parameter was provided in the request, which is not shown here as it's a pointer). #### Response Example ```json { "launchArgs": "--level 5", "outpath": "/Games/MyGame.pdx" } ``` ## POST /system/setSerialMessageCallback ### Description Provides a callback function to receive messages sent to the device over the serial port. ### Method POST ### Endpoint /system/setSerialMessageCallback ### Parameters #### Request Body - **callback** (function) - The callback function to execute when a serial message is received. Signature: `void callback(const char* data)`. ### Request Example ```json { "callback": "function(data) print('Received: ' .. data) end" } ``` ### Response #### Success Response (200) No content. ``` -------------------------------- ### Get file size - Playdate SDK Source: https://sdk.play.date/3.0.1/Inside%20Playdate Returns the size of the file at the specified path. ```Lua playdate.file.getSize(path) ``` -------------------------------- ### Code Profiling with `sample()` in Playdate Source: https://sdk.play.date/3.0.1/Inside%20Playdate Allows profiling specific sections of code by wrapping them in an anonymous function and passing it to `sample()`. This helps identify performance bottlenecks. Different code paths can be monitored using unique sample names. Requires importing `_CoreLibs/utilities/sampler`. ```lua -- Requires: import("_CoreLibs/utilities/sampler") sample("MyHeavyOperation", function() -- Code that might be slow for i = 1, 10000 do math.sqrt(i) end end) sample("AnotherTask", function() -- Other code to profile end) ``` -------------------------------- ### Basic C Project Structure for Playdate Source: https://sdk.play.date/3.0.1/Inside%20Playdate Outlines the essential files and structure for a C-based game project on Playdate. This includes the main C file, a Makefile, and potentially supporting header files. ```c // main.c #include int main(void) { // Game initialization playdate_graphics->clear(kColorBlack); playdate_graphics->setColor(kColorWhite); playdate_graphics->drawText("Hello from C!", 100, 120, kUTF8Encoding); // Game loop while (1) { playdate_sys->draw("frame"); // Draw the frame playdate_sys->processEvents(); // Handle input and system events } return 0; } // Makefile (simplified example) NAME = my_c_game # Include Playdate SDK path include $(PLAYDATE_SDK_PATH)/build_support/common.mk SOURCES = main.c # Link against necessary libraries LIBS = -lplaydate all: $(NAME).elf $(NAME).elf: $(OBJECTS) $(CC) $(OBJECTS) $(LIBS) -o $(NAME).elf include $(PLAYDATE_SDK_PATH)/build_support/rules.mk ``` -------------------------------- ### playdate.graphics.animator.reverses Source: https://sdk.play.date/3.0.1/Inside%20Playdate If set to true, after the animation reaches the end, it runs in reverse from the end to the start. ```APIDOC ## PUT /playdate.graphics.animator.reverses ### Description Enables reverse animation playback after completion. ### Method PUT ### Endpoint /playdate.graphics.animator.reverses ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **reverse** (boolean) - Whether to reverse the animation playback. ``` -------------------------------- ### Synth Volume Control Source: https://sdk.play.date/3.0.1/Inside%20Playdate%20with%20C Functions to set and get the playback volume for the left and right channels of the synth. ```APIDOC ## Synth Volume Control ### Description Functions to set and get the playback volume for the left and right channels of the synth. ### Methods #### `setVolume(PDSynth* synth, float lvol, float rvol)` Sets the playback volume (0.0 - 1.0) for the left and right (if stereo) channels of the synth. This is equivalent to `playdate->sound->source->setVolume((SoundSource*)synth, lvol, rvol)`. #### `getVolume(PDSynth* synth, float* outlvol, float* outrvol)` Gets the playback volume for the left and right (if stereo) channels of the synth. This is equivalent to `playdate->sound->source->getVolume((SoundSource*)synth, outlvol, outrvol)`. ``` -------------------------------- ### Display and Updates Source: https://sdk.play.date/3.0.1/Inside%20Playdate%20with%20C Manage screen updates and draw the FPS counter. ```APIDOC ## POST /system/setUpdateCallback ### Description Replaces the default Lua run loop function with a custom update function. The update function should return a non-zero number to indicate that the display needs updating. ### Method POST ### Endpoint /system/setUpdateCallback ### Parameters #### Request Body - **update** (function) - The custom update function. Signature: `int update(void* userdata)`. - **userdata** (any) - User data to pass to the update function. ### Request Example ```json { "update": "function(userdata) return 1 end", "userdata": null } ``` ### Response #### Success Response (200) No content. ## POST /system/drawFPS ### Description Calculates and draws the current frames per second at the specified coordinates. ### Method POST ### Endpoint /system/drawFPS ### Parameters #### Request Body - **x** (integer) - The x-coordinate for drawing the FPS. - **y** (integer) - The y-coordinate for drawing the FPS. ### Request Example ```json { "x": 10, "y": 10 } ``` ### Response #### Success Response (200) No content. ``` -------------------------------- ### System Utility Functions Source: https://sdk.play.date/3.0.1/Inside%20Playdate%20with%20C Core system utility functions for memory management, retrieving system information, and logging to the console ```APIDOC ## Memory Allocation ### playdate->system->realloc #### Description Allocates heap space if ptr is NULL, else reallocates the given pointer. If size is zero, frees the given pointer. #### Function Signature ```c void* playdate->system->realloc(void* ptr, size_t size); ``` #### Parameters - **ptr** (void*) - Required - Pointer to reallocate, or NULL to allocate new memory - **size** (size_t) - Required - New size in bytes, or 0 to free the pointer #### Returns Returns pointer to allocated/reallocated memory, or NULL if size is 0 and ptr was freed ## System Information ### playdate->system->getSystemInfo #### Description Returns a pointer to a struct containing info about the system. #### Function Signature ```c struct PDInfo* playdate->system->getSystemInfo(void); ``` #### Returns Returns pointer to PDInfo struct with system information #### PDInfo Struct ```c struct PDInfo { uint32_t osversion; PDLanguage language; } ``` #### Fields - **osversion** (uint32_t) - The OS version - **language** (PDLanguage) - The system language ## Logging Functions ### playdate->system->error #### Description Calls the log function, outputting an error in red to the console, then pauses execution. #### Function Signature ```c void playdate->system->error(const char* format, ...); ``` #### Parameters - **format** (const char*) - Required - printf-style format string - **...** (variable args) - Optional - Additional arguments for format string ### playdate->system->logToConsole #### Description Calls the log function. Equivalent to `print()` in the Lua API. #### Function Signature ```c void playdate->system->logToConsole(const char* format, ...); ``` #### Parameters - **format** (const char*) - Required - printf-style format string - **...** (variable args) - Optional - Additional arguments for format string ``` -------------------------------- ### Create and Draw a Tilemap (Playdate Lua) Source: https://sdk.play.date/3.0.1/Inside%20Playdate Demonstrates the basic steps to create, configure, and draw a tilemap in Playdate. This involves instantiating a tilemap, attaching an imagetable containing tile graphics, setting the tilemap layout using `setTiles()`, and finally drawing the tilemap to the screen. ```lua -- 1. Instantiate a blank tilemap. local myTilemap = playdate.graphics.tilemap.new() -- 2. Attach an imagetable (assuming 'tileSet' is a loaded imagetable). myTilemap:setImagetable(tileSet) -- 3. Set the tilemap's matrix of indices and width. -- (Assuming 'levelData' is a 2D array of tile indices and 'levelWidth' is its width) myTilemap:setTiles(levelData, levelWidth) -- 4. Draw your tilemap. myTilemap:draw(0, 0) ``` -------------------------------- ### Get System Language (Lua) Source: https://sdk.play.date/3.0.1/Inside%20Playdate Retrieves the current system language, returning either 'kLanguageEnglish' or 'kLanguageJapanese'. ```lua local currentLanguage = playdate.getSystemLanguage() ``` -------------------------------- ### Compile Playdate Project with pdc Command Source: https://sdk.play.date/3.0.1/Inside%20Playdate Basic pdc compilation command requiring source directory and output directory arguments. Output directory should use .pdx extension. Includes options for stripping debug info, setting library paths, and controlling verbosity. Multiple library paths can be specified. ```Bash $ pdc MyGameSource MyGame.pdx ``` ```Bash # Strip debugging information $ pdc -s MyGameSource MyGame.pdx # Set library paths $ export PLAYDATE_LIB_PATH=~/pddev/Libs $ pdc -I ~/pddev/OtherLibs MyGameSource MyGame.pdx # Additional options -v/--verbose: verbose mode, gives info about what the compiler is doing -q/--quiet: quiet mode, suppresses non-error output -k/--skip-unknown: skip unrecognized files instead of copying them to the pdx folder ``` -------------------------------- ### Get Network Status - C Source: https://sdk.play.date/3.0.1/Inside%20Playdate%20with%20C Returns the current network status. This helps to determine the network connection status of the Playdate device. ```C WifiStatus playdate->network->getStatus(); ``` -------------------------------- ### File Reading and Writing in Playdate Source: https://sdk.play.date/3.0.1/Inside%20Playdate Provides examples of how to read from and write to files using the Playdate SDK. This is essential for saving game state, loading assets, or managing persistent data. ```lua -- Writing to a file local file, err = playdate.file.open("savegame.dat", "w") if file then file:write("Player Score: 1000\n") file:close() else print("Error opening file for writing: " .. err) end -- Reading from a file local file, err = playdate.file.open("savegame.dat", "r") if file then local content = file:read() print("File content: " .. content) file:close() else print("Error opening file for reading: " .. err) end ``` -------------------------------- ### Get filesystem error (C) Source: https://sdk.play.date/3.0.1/Inside%20Playdate%20with%20C Returns human-readable error text. playdate->file->geterr(). No parameters. Returns const char*. ```c const char* playdate->file->geterr(void) ``` -------------------------------- ### Lua Object-Oriented Programming with CoreLibs Source: https://sdk.play.date/3.0.1/Inside%20Playdate Demonstrates creating classes, subclasses, initializing objects, and using built-in OOP features like 'isa' and 'tableDump' provided by the CoreLibs/object library. Requires importing the 'CoreLibs/object' module. Usage includes defining classes, their properties, and instance methods. ```lua import "CoreLibs/object" class('Tree').extends() -- or with properties -- class('Tree', {color = 'Brown'}).extends(Object) class('Oak').extends(Tree) function Oak:init(age, height) Oak.super.init(self, age) self.height = height end local oakInstance = Oak(10, 25) -- Accessing class name print(oakInstance.className) -- Output: Oak -- Checking if an instance is of a certain type print(oakInstance:isa(Tree)) -- Output: true -- Dumping object's properties oakInstance:tableDump() ``` -------------------------------- ### Get actual FPS (C/Lua) Source: https://sdk.play.date/3.0.1/Inside%20Playdate%20with%20C Returns measured refresh rate. In C: playdate->display->getFPS(). In Lua: playdate.display.getFPS(). No parameters. ```c float playdate->display->getFPS() ``` ```lua playdate.display.getFPS() ``` -------------------------------- ### Xcode Build Phase Script for PDX Compilation Source: https://sdk.play.date/3.0.1/Inside%20Playdate%20with%20C Run script phase in Xcode that copies the compiled Simulator library to pdex.dylib and invokes Make to build the .pdx bundle. Add this after compiling sources; uncheck dependency analysis for proper execution. Ensures the bundle is ready for Simulator launch. ```bash cp "${TARGET_BUILD_DIR}/${EXECUTABLE_NAME}" Source/pdex.dylib make pdx ``` -------------------------------- ### Create directory - Playdate SDK Source: https://sdk.play.date/3.0.1/Inside%20Playdate Creates a directory at the specified path, including any necessary intermediate directories. ```Lua playdate.file.mkdir(path) ``` ```C playdate->file->mkdir() ``` -------------------------------- ### Get LFO Value Source: https://sdk.play.date/3.0.1/Inside%20Playdate Retrieves the current output value of the LFO signal. This value can be used to modulate other audio parameters. ```lua playdate.sound.lfo:getValue() ``` -------------------------------- ### Get Current Font Tracking Source: https://sdk.play.date/3.0.1/Inside%20Playdate Retrieves the current global font tracking value in pixels, which affects the spacing between characters. ```lua local currentTracking = playdate.graphics.getFontTracking() ``` -------------------------------- ### Get TCP Connection Error (C) Source: https://sdk.play.date/3.0.1/Inside%20Playdate%20with%20C Retrieves the last error code associated with a TCP connection. Returns NET_OK if no error has occurred. ```c PDNetErr playdate->network->tcp->getError(TCPConnection* connection); ``` -------------------------------- ### System Settings Source: https://sdk.play.date/3.0.1/Inside%20Playdate%20with%20C Retrieve global system settings for screen orientation and reduced flashing. ```APIDOC ## GET /system/settings ### Description Retrieves global system settings. ### Method GET ### Endpoint /system/settings ### Parameters None ### Request Example None ### Response #### Success Response (200) - **flipped** (integer) - Returns 1 if the global "flipped" system setting is set, otherwise 0. - **reduceFlashing** (integer) - Returns 1 if the global "reduce flashing" system setting is set, otherwise 0. #### Response Example ```json { "flipped": 1, "reduceFlashing": 0 } ``` ``` -------------------------------- ### Get refresh rate (C/Lua) Source: https://sdk.play.date/3.0.1/Inside%20Playdate%20with%20C Returns current nominal refresh rate. In C: playdate->display->getRefreshRate(). In Lua: playdate.display.getRefreshRate(). No parameters. ```c float playdate->display->getRefreshRate() ``` ```lua playdate.display.getRefreshRate() ``` -------------------------------- ### Object-Oriented Programming with CoreLibs Source: https://sdk.play.date/3.0.1/Inside%20Playdate Details on how to use the `_CoreLibs/object` library for object-oriented programming in Lua, including class creation, inheritance, initialization, and instance management. ```APIDOC ## Object-Oriented Programming in Lua Lua does not have built-in object-oriented programming (OOP) support. The Playdate SDK's `_CoreLibs/object` library provides a basic OOP class system. ### Importing the Object Library ```lua import "CoreLibs/object" ``` ### Creating a New Class Use the `class()` function to define a new class. You can optionally specify properties and a namespace. If no parent class is provided, it defaults to `Object`. **Syntax:** ```lua class(ClassName, [properties], [namespace]).extends(ParentClass) ``` **Examples:** Creating a simple `Tree` class: ```lua class('Tree').extends() ``` Creating a `Tree` class with default properties: ```lua class('Tree', {color = 'Brown'}).extends(Object) ``` Creating a subclass of `Tree`: ```lua class('Oak').extends(Tree) ``` ### Class Initialization (`init` function) Subclasses can define an `init` function to initialize instances. It's crucial to call the superclass's `init` function correctly. **Syntax:** ```lua function SubclassName:init(arg1, arg2, ...) SubclassName.super.init(self, ...) -- Additional initialization logic end ``` **Example:** ```lua function Oak:init(age, height) Oak.super.init(self, age) -- Calls the superclass's init self.height = height end ``` ### Creating Class Instances Instantiate a class by calling it like a function. **Example:** ```lua oakInstance = Oak(age, height) ``` ### Accessing Class Name Instances have a `_className_` property. ```lua print(oakInstance._className_) -- Output: 'Oak' ``` ### Checking Class Type (`isa()`) Use the `isa()` function to check if an instance belongs to a specific class or inherits from it. ```lua print(oakInstance:isa(Tree)) -- Returns true if oakInstance is an instance of Oak or a subclass of Oak ``` ### Debugging (`tableDump()`) The `Object:tableDump()` function prints the key/value pairs of an object and its superclasses. ```lua oakInstance:tableDump() ``` ``` -------------------------------- ### Create Value Timer - Lua Source: https://sdk.play.date/3.0.1/Inside%20Playdate Creates a new Playdate timer for animating a value from a start to an end value over a specified duration. ```Lua playdate.timer.new(duration, [startValue, endValue, [easingFunction]]) ``` -------------------------------- ### List files (C/Lua) Source: https://sdk.play.date/3.0.1/Inside%20Playdate%20with%20C Calls callback for each file in path. In C: playdate->file->listfiles(). In Lua: playdate.file.listFiles(). Takes path, callback, userdata, showhidden params. ```c int playdate->file->listfiles(const char* path, void (*callback)(const char* filename, void* userdata), void* userdata, int showhidden) ``` ```lua playdate.file.listFiles(path, callback, showhidden) ```