### Example Leaderboard Score Upload (Lua) Source: https://github.com/uspgamedev/luasteam/blob/master/docs/user_stats.rst An example helper function demonstrating how to upload a user's score to a leaderboard using `userStats.uploadLeaderboardScore`. It handles the callback to check for success or failure and prints the new rank if successful. ```lua function uploadScoresHelper(handle) local score = getScore() -- Assumes getScore() is defined elsewhere Steam.userStats.uploadLeaderboardScore(handle, "KeepBest", score, nil, function(data, err) if err or not data.success then print('Upload score failed') else print('Upload score success. New rank is: ' .. data.globalRankNew) end end) end ``` -------------------------------- ### Get Item Install Info - LuaSteam Source: https://github.com/uspgamedev/luasteam/blob/master/docs/UGC.rst Fetches information about installed Steam Workshop content. It returns the size, absolute path, and last update time for an installed item. This function is crucial for accessing and managing local workshop files. ```lua .. function:: UGC.getItemInstallInfo (id) :returns: (`boolean`) **true** if the operation is successfull. **false** in the following cases: * cchFolderSize is 0. * The workshop item has no content. * The workshop item is not installed. If this value is **false**, nothing else is returned. Otherwise: :returns: (`number`) Returns the size of the workshop item in bytes. :returns: (`string`) Returns the absolute path to the folder containing the content. :returns: (`number`) Returns the time when the workshop item was last updated. :SteamWorks: `GetItemInstallInfo `_ Gets info about currently installed content on the disc for workshop items that have ``installed`` set. Calling this sets the "used" flag on the workshop item for the current player and adds it to their ``usedOrPlayed`` list. If ``legacyItem`` is set then folder contains the path to the legacy file itself, not a folder. ``` -------------------------------- ### Sphinx Documentation Build Source: https://github.com/uspgamedev/luasteam/blob/master/CONTRIBUTING.md Installs Sphinx and the ReadTheDocs theme for building project documentation. Assumes Python and pip are available. The 'make html' command is run from within the 'docs/' directory. ```bash pip install sphinx sphinx-rtd-theme cd docs/ make html ``` -------------------------------- ### UGC.getItemState Source: https://github.com/uspgamedev/luasteam/blob/master/docs/UGC.rst Gets the current state of a workshop item on this client. It returns a table with boolean flags indicating the item's subscription status, installation status, download progress, and more. ```APIDOC ## GET /ugc/getItemState ### Description Gets the current state of a workshop item on this client. It returns a table with boolean flags indicating the item's subscription status, installation status, download progress, and more. ### Method GET ### Endpoint /ugc/getItemState ### Parameters #### Path Parameters - **publishedFileId** (uint64) - Required - The workshop item to get the state for. ### Response #### Success Response (200) - **subscribed** (boolean) - The current user is subscribed to this item. - **legacyItem** (boolean) - The item was created with the old workshop functions. - **installed** (boolean) - Item is installed and usable. - **needsUpdate** (boolean) - The item needs an update. - **downloading** (boolean) - The item update is currently downloading. - **downloadPending** (boolean) - downloadItem was called, and content is not yet available. #### Response Example ```json { "subscribed": true, "legacyItem": false, "installed": true, "needsUpdate": false, "downloading": false, "downloadPending": false } ``` ``` -------------------------------- ### UGC.getItemInstallInfo Source: https://github.com/uspgamedev/luasteam/blob/master/docs/UGC.rst Gets info about currently installed content on the disc for workshop items that have 'installed' set. Returns the size, absolute path, and last updated time of the workshop item. ```APIDOC ## GET /ugc/getItemInstallInfo ### Description Gets info about currently installed content on the disc for workshop items that have 'installed' set. Returns the size, absolute path, and last updated time of the workshop item. ### Method GET ### Endpoint /ugc/getItemInstallInfo ### Parameters #### Path Parameters - **id** (uint64) - Required - The ID of the workshop item. ### Response #### Success Response (200) - **size** (number) - The size of the workshop item in bytes. - **path** (string) - The absolute path to the folder containing the content. - **lastUpdated** (number) - The time when the workshop item was last updated. #### Response Example ```json { "size": 102400, "path": "/path/to/workshop/item", "lastUpdated": 1678886400 } ``` ``` -------------------------------- ### UGC.startPlaytimeTracking Source: https://github.com/uspgamedev/luasteam/blob/master/docs/UGC.rst Starts tracking playtime on a set of workshop items. The callback is called asynchronously with the result of the operation. ```APIDOC ## POST /ugc/startPlaytimeTracking ### Description Starts tracking playtime on a set of workshop items. The callback is called asynchronously with the result of the operation. ### Method POST ### Endpoint /ugc/startPlaytimeTracking ### Parameters #### Request Body - **vec** (array[uint64]) - Required - An array of workshop item IDs (PublishedFileId) to track. Maximum of 100 items. ### Request Example ```json { "vec": [ 1234567890, 9876543210 ] } ``` ### Response #### Success Response (200) - **result** (number) - The result of the operation (EResult). #### Response Example ```json { "result": 1 } ``` ``` -------------------------------- ### Get Subscribed Workshop Items with Lua Source: https://context7.com/uspgamedev/luasteam/llms.txt Retrieves a list of all Workshop items a player is subscribed to using luasteam. It fetches item IDs, checks their states (subscribed, installed, downloading, needs update), and retrieves installation details if the item is installed. ```lua local steam = require("luasteam") -- Get subscribed items local num_items = steam.UGC.getNumSubscribedItems() print("Subscribed to", num_items, "workshop items") if num_items > 0 then local item_ids = steam.UGC.getSubscribedItems() for i, item_id in ipairs(item_ids) do -- Check item state local state = steam.UGC.getItemState(item_id) if state then print("Item", i, "ID:", tostring(item_id)) print(" Subscribed:", state.subscribed) print(" Installed:", state.installed) print(" Downloading:", state.downloading) print(" Needs update:", state.needsUpdate) -- Get install info if installed if state.installed then local success, size, folder, timestamp = steam.UGC.getItemInstallInfo(item_id) if success then print(" Folder:", folder) print(" Size on disk:", size, "bytes") print(" Install timestamp:", timestamp) -- Load mod from folder load_mod(folder) end end end end end ``` -------------------------------- ### Get Launch Command Line (Lua) Source: https://github.com/uspgamedev/luasteam/blob/master/docs/apps.rst Retrieves the command line parameters used to launch the game. Useful for parsing connect strings for game invites. Currently limited to 1024 characters. ```Lua local params = Steam.apps.getLaunchCommandLine() local connect_string = tryParseConnectString(params) if connect_string then initiateJoinGame(connect_string) end ``` -------------------------------- ### Build LuaSteam for Windows 64-bit Source: https://github.com/uspgamedev/luasteam/blob/master/CONTRIBUTING.md Compiles the LuaSteam project for a 64-bit Windows environment. Requires Visual Studio 2017 Community and MinGW installed via Chocolatey. Uses mingw32-make for building. ```bash choco install visualstudio2017community visualstudio2017-workload-nativecrossplat mingw mingw32-make windows64 ``` -------------------------------- ### Configure Network Connection Options (Lua) Source: https://github.com/uspgamedev/luasteam/blob/master/docs/networking_sockets.rst This example demonstrates setting various network configuration options when initiating connections. Options include encryption, authentication, and Nagle time. It's important to understand the implications of each setting before modifying them, especially in production environments. ```lua { Unencrypted = 2, IP_AllowWithoutAuth = 1, NagleTime = 0} ``` -------------------------------- ### Build LuaSteam for macOS Source: https://github.com/uspgamedev/luasteam/blob/master/CONTRIBUTING.md Compiles the LuaSteam project for macOS. Requires luajit to be installed via Homebrew. Uses the 'osx' target in the Makefile. ```bash brew install luajit make osx ``` -------------------------------- ### LuaSteaM Sockets Client Example Source: https://github.com/uspgamedev/luasteam/blob/master/docs/networking_sockets.rst This Lua code demonstrates how to initialize LuaSteaM, connect to a server by IP address, send messages, and receive messages. It requires Lua 5.1+ or Löve. The primary function is establishing and maintaining a reliable connection. ```lua local Steam = require 'luasteam' local connection = nil Steam.init() Steam.networkingSockets.initAuthentication() function Steam.networkingSockets.onConnectionChanged(data) print ('Connection changed', data.connection, data.state, data.state_old, data.endReason, data.debug) end function Steam.networkingSockets.onAuthenticationStatus(data) if data.status == 100 and not connection then connection = Steam.networkingSockets.connectByIPAddress("127.0.0.1:55556") end end local run = true local counter = 0 local msg_rec = false while run do Steam.runCallbacks() if connection then local n, messages = Steam.networkingSockets.receiveMessagesOnConnection(connection) if n > 0 then for j,m in ipairs(messages) do print("received message", j, m, "from connection", connection, type(j)) Steam.networkingSockets.sendMessageToConnection(connection, "Hello server! This is the client! Thank you!", Steam.networkingSockets.flags.Send_Reliable) msg_rec = true end end end if msg_rec then counter = counter + 1 if counter > 10000 then -- you might have to increase this if the client shuts down faster than the message can be sent run = false end end end if connection then Steam.networkingSockets.closeConnection(connection) end Steam.shutdown() ``` -------------------------------- ### Get Game Language and DLC Status with LuaSteam Source: https://context7.com/uspgamedev/luasteam/llms.txt Retrieves application-specific information such as the game's language and DLC installation status using LuaSteam. It also handles game launch parameters and URL-based launches. Requires the luasteam library. ```lua local steam = require("luasteam") -- Get Steam's configured language local language = steam.apps.getCurrentGameLanguage() print("Game language:", language) -- e.g., "english", "japanese", "french" -- Load localized strings based on language load_localization(language) -- Check if DLC is installed local dlc_app_id = 12345 if steam.apps.isDlcInstalled(dlc_app_id) then print("DLC is installed, enabling bonus content") enable_bonus_content() else print("DLC not installed") end -- Get launch command line parameters local launch_params = steam.apps.getLaunchCommandLine() if launch_params and launch_params ~= "" then print("Launch parameters:", launch_params) parse_launch_params(launch_params) end -- Callback when launched with URL steam.apps.onNewUrlLaunchParameters = function() print("Game launched with new URL parameters") local params = steam.apps.getLaunchCommandLine() handle_url_launch(params) end ``` -------------------------------- ### Build LuaSteam for Windows 32-bit Source: https://github.com/uspgamedev/luasteam/blob/master/CONTRIBUTING.md Compiles the LuaSteam project for a 32-bit Windows environment. Requires Visual Studio 2017 Community and MinGW installed via Chocolatey. Uses mingw32-make for building. ```bash choco install visualstudio2017community visualstudio2017-workload-nativecrossplat mingw mingw32-make windows32 ``` -------------------------------- ### LuaSteaM Sockets Server Example Source: https://github.com/uspgamedev/luasteam/blob/master/docs/networking_sockets.rst This Lua code demonstrates how to set up a LuaSteaM server to listen for incoming connections, accept them, send messages, and handle disconnection events. It requires Lua 5.1+ or Löve. The server listens on a specified IP address and port. ```lua local Steam = require 'luasteam' local connections = {} local server = nil Steam.init() Steam.networkingSockets.initAuthentication() function Steam.networkingSockets.onConnectionChanged(data) print ('Connection changed', data.connection, data.state, data.state_old, data.endReason, data.debug) if data.state == "Connecting" then Steam.networkingSockets.acceptConnection(data.connection) end if data.state == "Connected" then connections[data.connection] = true Steam.networkingSockets.sendMessageToConnection(data.connection, "Hello client! This is the server! Welcome!", Steam.networkingSockets.flags.Send_Reliable) end if data.state == "ClosedByPeer" or data.state == "ProblemDetectedLocally" then print(data.connection, data.state, data.endReason, data.debug) Steam.networkingSockets.closeConnection(data.connection) connections[data.connection] = nil end end function Steam.networkingSockets.onAuthenticationStatus(data) if data.status == 100 and not connection then server = Steam.networkingSockets.createListenSocketIP("[::]:55556") print("Listening on port 55556") end end local run = true while run do Steam.runCallbacks() for conn,_ in pairs(connections) do local n, messages = Steam.networkingSockets.receiveMessagesOnConnection(conn) if n > 0 then for j,m in ipairs(messages) do print("received message", j, m, "from connection", conn, type(j)) run = false end end end end for conn,_ in pairs(connections) do Steam.networkingSockets.closeConnection(conn) end Steam.shutdown() ``` -------------------------------- ### Input API - Get Connected Controllers Source: https://github.com/uspgamedev/luasteam/blob/master/docs/input.rst Returns a list of handles for all currently connected controllers. This is essential for managing input from multiple controllers. ```APIDOC ## GetConnectedControllers ### Description Returns a list of handles for all currently connected controllers. ### Method GET ### Endpoint `/GetConnectedControllers` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **inputHandles** (table) - An array filled with the `inputHandles` (`uint64`) of currently connected controllers. #### Response Example ```json { "inputHandles": [ "9876543210987654321", "1234567890123456789" ] } ``` ``` -------------------------------- ### Configure Action Sets and Get Button Input with LuaSteam Source: https://context7.com/uspgamedev/luasteam/llms.txt This snippet illustrates how to configure action sets and retrieve digital and analog input from controllers using the Steam Input API. It involves getting action set and action handles, activating action sets based on game state, and reading input data in a game loop. Key functions include `steam.input.getActionSetHandle`, `steam.input.getDigitalActionHandle`, `steam.input.activateActionSet`, `steam.input.getDigitalActionData`, and `steam.input.getAnalogActionData`. Input is controller and action data, with output being player actions like jumping or movement. ```lua local steam = require("luasteam") -- Get action set and action handles local menu_action_set = steam.input.getActionSetHandle("MenuControls") local game_action_set = steam.input.getActionSetHandle("InGameControls") local jump_action = steam.input.getDigitalActionHandle("Jump") local move_action = steam.input.getAnalogActionHandle("Move") local controller = steam.input.getControllerForGamepadIndex(0) -- Activate action set for current game state function enter_game() steam.input.activateActionSet(controller, game_action_set) end function enter_menu() steam.input.activateActionSet(controller, menu_action_set) -- Or activate for all controllers steam.input.activateActionSet("all", menu_action_set) end -- In game loop, read input function love.update(dt) steam.runCallbacks() -- Get digital action (button press) local jump_data = steam.input.getDigitalActionData(controller, jump_action) if jump_data.active and jump_data.state then player:jump() end -- Get analog action (stick/pad) local move_data = steam.input.getAnalogActionData(controller, move_action) if move_data.active then player:move(move_data.x, move_data.y) print("Movement mode:", move_data.mode) -- "JoystickMove", "Dpad", etc. end end ``` -------------------------------- ### Build LuaSteam for Linux 64-bit Source: https://github.com/uspgamedev/luasteam/blob/master/CONTRIBUTING.md Compiles the LuaSteam project for a 64-bit Linux environment. Requires libluajit-5.1-dev. The GNU_IPATHS variable in the Makefile might need adjustment for specific LuaJIT installations. ```bash sudo apt-get update && sudo apt-get install libluajit-5.1-dev make linux64 ``` -------------------------------- ### Subscribe to a Workshop Item (Lua) Source: https://github.com/uspgamedev/luasteam/blob/master/docs/UGC.rst Subscribes the user to a specific Steam Workshop item, initiating its download and installation. It requires the item's ID and a callback function. The callback processes the result, including the published file ID and any errors encountered during the subscription process. ```lua -- Note: itemID is uint64, not a standard Lua number! Steam.UGC.subscribeItem(itemID, function(data, err) if not err and data.result == 1 then print('Successfully subscribed to ' .. itemID .. '!') end end) ``` -------------------------------- ### Create and Upload Workshop Item with Lua Source: https://context7.com/uspgamedev/luasteam/llms.txt Allows creation of a new Workshop item and subsequent upload of content using luasteam. It involves creating the item, starting an update, setting item properties (title, description, content, preview), and submitting the update. It also includes progress monitoring for the upload. ```lua local steam = require("luasteam") local update_handle = nil -- Step 1: Create item local function on_item_created(result, io_fail) if io_fail or result.result ~= 1 then print("Failed to create item") return end print("Item created! Published File ID:", tostring(result.publishedFileId)) if result.userNeedsToAcceptWorkshopLegalAgreement then print("User needs to accept Workshop legal agreement") end -- Step 2: Start item update local app_id = steam.utils.getAppID() update_handle = steam.UGC.startItemUpdate(app_id, result.publishedFileId) -- Step 3: Set item properties steam.UGC.setItemTitle(update_handle, "My Awesome Mod") steam.UGC.setItemDescription(update_handle, "This mod adds amazing features!") steam.UGC.setItemContent(update_handle, "/path/to/mod/folder") steam.UGC.setItemPreview(update_handle, "/path/to/preview.jpg") -- Step 4: Submit update steam.UGC.submitItemUpdate(update_handle, "Initial upload", on_item_updated) end local function on_item_updated(result, io_fail) if io_fail or result.result ~= 1 then print("Failed to update item") return end print("Item uploaded successfully!") end -- Create item -- File types: "Community", "Microtransaction", "Collection", "Art", "Video", -- "Screenshot", "WebGuide", "IntegratedGuide", "Merch", -- "ControllerBinding", "SteamVideo", "GameManagedItem" local app_id = steam.utils.getAppID() steam.UGC.createItem(app_id, "Community", on_item_created) -- Monitor upload progress function love.update(dt) if update_handle then local status, processed, total = steam.UGC.getItemUpdateProgress(update_handle) print(string.format("Upload: %s - %d/%d bytes", status, processed, total)) end end ``` -------------------------------- ### Input API - Get Controller For Gamepad Index Source: https://github.com/uspgamedev/luasteam/blob/master/docs/input.rst Retrieves the controller handle associated with a given emulated gamepad index. This is useful when integrating with systems that use gamepad indexing. ```APIDOC ## GetControllerForGamepadIndex ### Description Retrieves the controller handle associated with a given emulated gamepad index. ### Method GET ### Endpoint `/GetControllerForGamepadIndex` ### Parameters #### Path Parameters None #### Query Parameters - **index** (int) - Required - The index of the emulated gamepad you want to get a controller handle for. #### Request Body None ### Request Example ```json { "index": 0 } ``` ### Response #### Success Response (200) - **inputHandle** (number) - The `inputHandle` (`uint64`) of the associated controller handle for the specified emulated gamepad. #### Response Example ```json { "inputHandle": "9876543210987654321" } ``` ``` -------------------------------- ### Start Playtime Tracking - LuaSteam Source: https://github.com/uspgamedev/luasteam/blob/master/docs/UGC.rst Initiates playtime tracking for a specified list of workshop items. This function is used to log user engagement with workshop content. It accepts an array of item IDs and a callback function to handle the asynchronous response. ```lua .. function:: UGC.startPlaytimeTracking (vec, callback) :param table vec: The array of workshop items (`PublishedFileId`, more precisely `uint64`) you want to start tracking. (Maximum of 100 items.) :param function callback: Called asynchronously when this function returns. It is only called if you send between 1 and 100 items. See below. :returns: nothing :SteamWorks: `StartPlaytimeTracking `_ Start tracking playtime on a set of workshop items. When your app shuts down, playtime tracking will automatically stop. **callback(data, err)** receives two arguments: * **data** (`table`) -- Similar to `StartPlaytimeTrackingResult_t `_, or **nil** if **err** is **true**. * **data.result** (`number`) -- The result of the operation. See `EResult `_. * **err** (`boolean`): **true** if there was any IO error with the request. **Example**:: -- Tracks all subscribed items (you probably shouldn't do this) Steam.UGC.startPlaytimeTracking(Steam.UGC.getSubscribedItems(), function(data, err) ``` -------------------------------- ### Initialize SteamAPI using Lua Source: https://github.com/uspgamedev/luasteam/blob/master/docs/steam_api.rst Initializes the Steamworks API. This function must be called first after loading the library. It returns true if successful, indicating that all required interfaces are acquired. False indicates issues such as the Steam client not running, missing steam_appid.txt, OS user context mismatches, license verification failures, or incomplete App ID setup. ```lua local Steam = require 'luasteam' if not Steam.init() then error("Steam couldn't initialize") end ``` -------------------------------- ### Input API - Get Analog Action Origins Source: https://github.com/uspgamedev/luasteam/blob/master/docs/input.rst Retrieves the input origins for an analog action within a given action set and controller. This is useful for displaying the correct on-screen prompts to the user. ```APIDOC ## GetAnalogActionOrigins ### Description Retrieves the input origins for an analog action within a given action set and controller. ### Method GET ### Endpoint `/GetAnalogActionOrigins` ### Parameters #### Path Parameters None #### Query Parameters - **inputHandle** (uint64) - Required - The handle of the controller you want to query. Obtained from `input.getConnectedControllers`. - **actionSetHandle** (uint64) - Required - The handle of the action set you want to query. This can be obtained from `input.getActionSetHandle`. - **analogActionHandle** (uint64) - Required - The handle of the analog action you want to query. This can be obtained from `input.getAnalogActionHandle`. #### Request Body None ### Request Example ```json { "inputHandle": "9876543210987654321", "actionSetHandle": "1122334455667788990", "analogActionHandle": "1234567890123456789" } ``` ### Response #### Success Response (200) - **origins** (table) - An array filled with origins (`EInputActionOrigin`, ie `string`); see `EInputActionOrigin `_ for an analog action within an action set. #### Response Example ```json { "origins": [ "k_EInputActionOrigin_LeftStick", "k_EInputActionOrigin_RightTriggerAxis" ] } ``` ``` -------------------------------- ### Initialize and Shutdown luasteam Source: https://github.com/uspgamedev/luasteam/blob/master/docs/getting_started.rst Demonstrates the basic initialization and shutdown process for the luasteam library, mirroring the Steamworks API. Ensure Steam is running and a 'steam_appid.txt' file is present during development. ```Lua local Steam = require 'luasteam' Steam.init() -- ... -- when game is closing Steam.shutdown() ``` -------------------------------- ### ISteamApps - getLaunchCommandLine Source: https://github.com/uspgamedev/luasteam/blob/master/docs/apps.rst Retrieves the launch command-line parameters passed to the game. ```APIDOC ## GET /steam/apps/getLaunchCommandLine ### Description Gets the launch command line parameters. Use it to for example parse it for a connect string when implementing game invite functionality. ### Method GET ### Endpoint /steam/apps/getLaunchCommandLine ### Parameters #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **commandLine** (string) - The launch command line parameters. Maximum 1024 characters. #### Response Example { "commandLine": "+connect 192.168.1.100" } ``` -------------------------------- ### ISteamGameServer Initialization and Management Source: https://github.com/uspgamedev/luasteam/blob/master/docs/game_server.rst This section covers the core functions for initializing, running callbacks, and shutting down the ISteamGameServer interface. ```APIDOC ## ISteamGameServer Initialization and Management ### Description Functions for initializing the game server, running callbacks, and shutting down the interface. ### gameServer.init() #### Description Initiates the game server API, enabling ISteamNetworkingSockets and ISteamNetworkingUtils. This function adds metadata about the server type, which is particularly relevant for Steam's server browser feature. #### Parameters * **unIP** (int) - Required - The IP address to bind to (host order). Use `0` to bind to all local IPv4 addresses. * **steamPort** (int) - Required - The port clients will bind to. Essential for connecting to a game master and appearing in server lists. * **queryPort** (int) - Required - The port for communicating with a game master and exchanging status information. * **serverMode** (int) - Required - The server mode. Use constants from `Steam.gameServer.mode.*`: * `NoAuthentication`: No user login authentication, not listed on the server list. * `Authentication`: Authenticates users, lists on the server list, no VAC on clients. * `AuthenticationAndSecure`: Authenticates users, lists on the server list, and performs VAC protection on clients. * **version** (string) - Required - The game version in "x.x.x.x" format, used for server browser display and blocking outdated servers. #### Returns * (boolean) - `true` if initialization was successful, `false` otherwise. #### Example ```lua local result = Steam.gameServer.init(0, gamePort, queryPort, Steam.gameServer.mode.Authentication, "0.0.0.1") ``` ### gameServer.shutdown() #### Description Shuts down the game server interface. This should be called when the game is closing or the interface is no longer needed. #### Returns * nothing #### Example ```lua Steam.gameServer.shutdown() ``` ### gameServer.runCallbacks() #### Description Processes Steam callbacks. This function must be called regularly (e.g., within the main game loop) to receive updates and events from the Steam API. #### Returns * nothing #### Example ```lua Steam.gameServer.runCallbacks() ``` ``` -------------------------------- ### Detect Controllers and Get Input with LuaSteam Source: https://context7.com/uspgamedev/luasteam/llms.txt This code snippet shows how to initialize the Steam Input system, detect connected controllers, and retrieve information about each controller, including its type and gamepad index. It uses `luasteam` functions such as `steam.input.init`, `steam.input.getConnectedControllers`, `steam.input.getInputTypeForHandle`, and `steam.input.getControllerForGamepadIndex`. The output includes the number of controllers found and their respective types and indices. ```lua local steam = require("luasteam") -- Initialize Input system -- Pass true if you want to manually call runFrame() steam.input.init(false) -- Get all connected controllers local controllers = steam.input.getConnectedControllers() print("Found", #controllers, "controllers") for i, controller_handle in ipairs(controllers) do -- Get controller type local controller_type = steam.input.getInputTypeForHandle(controller_handle) print("Controller", i, "type:", controller_type) -- Types: "SteamController", "XBox360Controller", "XBoxOneController", -- "PS4Controller", "PS5Controller", "SwitchProController", etc. -- Map to gamepad index (for compatibility) local gamepad_index = steam.input.getGamepadIndexForController(controller_handle) print(" Gamepad index:", gamepad_index) end -- Get specific controller by gamepad index local primary_controller = steam.input.getControllerForGamepadIndex(0) ``` -------------------------------- ### Get Item State - LuaSteam Source: https://github.com/uspgamedev/luasteam/blob/master/docs/UGC.rst Retrieves the current state of a Steam Workshop item on the client. It returns a table of boolean flags indicating subscription status, installation, update needs, and download progress. This function is useful for managing local workshop content. ```lua print('Install location: ' .. folder) print('Install size: ' .. sizeOnDisk) elseif flag.downloading then print('Subscribed item is downloading!') else print('Subscribed item is doing something') end end .. function:: UGC.getItemState (publishedFileId) :param uint64 publishedFileId: The workshop item to get the state for. :returns: (`table`) A table with flags for the item state, or nil if the item is not tracked on client. All flags are boolean values. * **subscribed** -- The current user is subscribed to this item. Not just cached. * **legacyItem** -- The item was created with the old workshop functions in ISteamRemoteStorage. * **installed** -- Item is installed and usable (but maybe out of date). * **needsUpdate** -- The items needs an update. Either because it's not installed yet or creator updated the content. * **downloading** -- The item update is currently downloading. * **downloadPending** -- :func:`UGC.downloadItem` **(missing)** was called for this item, the content isn't available until the callback is fired. :SteamWorks: `GetItemState `_ Gets the current state of a workshop item on this client. ``` -------------------------------- ### ISteamInput Initialization and Shutdown Source: https://github.com/uspgamedev/luasteam/blob/master/docs/input.rst Functions to initialize and shut down the ISteamInput interface. Init must be called before using other ISteamInput functions, and shutdown should be called when finished. ```APIDOC ## POST /ISteamInput/Init ### Description Initializes the ISteamInput interface. This must be called before using any other ISteamInput functions. You can optionally set `explicitlyCallRunFrame` to `true` if you intend to manually call `input.runFrame()` each frame; otherwise, it will be called automatically when `Steam.runCallbacks()` is invoked. ### Method POST ### Endpoint /ISteamInput/Init ### Parameters #### Query Parameters - **explicitlyCallRunFrame** (boolean) - Optional - If `true`, requires manual calls to `input.runFrame()` each frame. Otherwise, `Steam.runCallbacks()` handles it automatically. ### Response #### Success Response (200) - **success** (boolean) - Indicates if the initialization was successful. Always returns `true`. ### Request Example ```json { "explicitlyCallRunFrame": false } ``` ### Response Example ```json { "success": true } ``` --- ## POST /ISteamInput/Shutdown ### Description Shuts down the ISteamInput interface. This should be called when you are finished with all ISteamInput operations. ### Method POST ### Endpoint /ISteamInput/Shutdown ### Parameters _None_ ### Response #### Success Response (200) - **success** (boolean) - Indicates if the shutdown was successful. Always returns `true`. ### Request Example ```json { } ``` ### Response Example ```json { "success": true } ``` ``` -------------------------------- ### Input API - Get Analog Action Handle Source: https://github.com/uspgamedev/luasteam/blob/master/docs/input.rst Gets the handle for a specified analog action name. This is typically used to get a numerical identifier for an analog input defined in the game's configuration files. ```APIDOC ## GetAnalogActionHandle ### Description Gets the handle for a specified analog action name. ### Method GET ### Endpoint `/GetAnalogActionHandle` ### Parameters #### Path Parameters None #### Query Parameters - **actionName** (string) - Required - The string identifier of the analog action defined in the game's VDF file. #### Request Body None ### Request Example ```json { "actionName": "move_left_stick" } ``` ### Response #### Success Response (200) - **handle** (number) - The handle (`InputAnalogActionHandle`, ie `uint64`) of the specified analog action. #### Response Example ```json { "handle": "1234567890123456789" } ``` ``` -------------------------------- ### Check DLC Installation (Lua) Source: https://github.com/uspgamedev/luasteam/blob/master/docs/apps.rst Checks if a specific DLC is owned and installed for the current user. Requires the App ID of the DLC as a numeric input. Returns a boolean indicating the installation status. ```Lua if Steam.apps.isDlcInstalled(12345) then -- Unlock game content end ``` -------------------------------- ### Input API - Get Digital Action Handle Source: https://github.com/uspgamedev/luasteam/blob/master/docs/input.rst Gets the handle for a specified digital action name. This is used to obtain a numerical identifier for digital inputs like buttons. ```APIDOC ## GetDigitalActionHandle ### Description Gets the handle for a specified digital action name. ### Method GET ### Endpoint `/GetDigitalActionHandle` ### Parameters #### Path Parameters None #### Query Parameters - **actionName** (string) - Required - The string identifier of the digital action defined in the game's VDF file. #### Request Body None ### Request Example ```json { "actionName": "jump_button" } ``` ### Response #### Success Response (200) - **handle** (number) - The handle (`InputDigitalActionHandle`, ie `uint64`) of the specified digital action. #### Response Example ```json { "handle": "1111111111111111111" } ``` ``` -------------------------------- ### Input API - Get Current Action Set Source: https://github.com/uspgamedev/luasteam/blob/master/docs/input.rst Gets the handle of the currently active action set for a specific controller. This helps in understanding which set of actions is currently in effect. ```APIDOC ## GetCurrentActionSet ### Description Gets the handle of the currently active action set for a specific controller. ### Method GET ### Endpoint `/GetCurrentActionSet` ### Parameters #### Path Parameters None #### Query Parameters - **inputHandle** (uint64) - Required - The handle of the controller you want to query. Obtained from `input.getConnectedControllers`. #### Request Body None ### Request Example ```json { "inputHandle": "9876543210987654321" } ``` ### Response #### Success Response (200) - **actionSetHandle** (number) - The `InputActionSetHandle` (`uint64`) handle of the action set activated for the specified controller. #### Response Example ```json { "actionSetHandle": "1122334455667788990" } ``` ``` -------------------------------- ### Network Configuration Options Source: https://github.com/uspgamedev/luasteam/blob/master/docs/networking_sockets.rst Details on the various network configuration options that can be passed when initiating connections. ```APIDOC ## Network Configuration Options Network options can be provided as a table when initiating connections. Use these with caution and only if you understand their implications. ### Example Configuration ```lua { Unencrypted = 2, IP_AllowWithoutAuth = 1, NagleTime = 0 } ``` ### Available Options (all values are integers): * **TimeoutInitial** (int): Timeout value in milliseconds for the initial connection attempt. * **TimeoutConnected** (int): Timeout value in milliseconds after the connection has been established. * **SendBufferSize** (int): Upper limit in bytes for buffered pending send data. Defaults to 512KB (524288 bytes). If this limit is reached, `SendMessage` will return `k_EResultLimitExceeded`. * **SendRateMin** (int): Minimum allowed send rate in bytes per second. Default is 0 (no limit). This controls the minimum send rate that bandwidth estimation can reach. * **SendRateMax** (int): Maximum allowed send rate in bytes per second. Default is 0 (no limit). This controls the maximum send rate that bandwidth estimation can reach. * **NagleTime** (int): Nagle time in microseconds. This determines how long to wait before sending small packets to facilitate grouping. Default is 5000 microseconds (5ms). * **IP_AllowWithoutAuth** (int): If set to 1, IP connections that lack strong authentication will not automatically fail. On clients, this allows connection attempts even without a known identity or certificate. On servers, it prevents automatic rejection of connections due to authentication failures, allowing manual examination and acceptance. **Note:** This is a developer configuration value and should not be exposed to users in production. * **MTU_PacketSize** (int): The maximum payload size in bytes for UDP packets. If set, `k_ESteamNetworkingConfig_MTU_DataSize` is automatically adjusted. * **Unencrypted** (int): Controls the allowance of unencrypted communication. * `0`: Not allowed (default). * `1`: Allowed, but encrypted communication is preferred. * `2`: Allowed, and encrypted communication is preferred. * `3`: Required. The connection will fail if the peer requires encryption. **Note:** This is a developer configuration value and should not be exposed to users in production. It also requires the peer to modify their value for encryption to be disabled. * **SymmetricConnect** (int): Set to `1` on outbound connections and listen sockets to enable "symmetric connect mode". This is useful for peer-to-peer use cases where peers are considered equal (neither is clearly the client or server). ``` -------------------------------- ### Input API - Get Analog Action Data Source: https://github.com/uspgamedev/luasteam/blob/master/docs/input.rst Retrieves data for a specified analog action handle. This function is useful for getting the current state of analog inputs like joysticks or triggers. ```APIDOC ## GetAnalogActionData ### Description Retrieves the current state of a supplied analog game action. ### Method GET ### Endpoint `/GetAnalogActionData` ### Parameters #### Path Parameters None #### Query Parameters - **analogActionHandle** (uint64) - Required - A handle to an analog action. This can be obtained from `input.getAnalogActionHandle`. #### Request Body None ### Request Example ```json { "analogActionHandle": "1234567890123456789" } ``` ### Response #### Success Response (200) - **InputAnalogActionData** (table) - A table with fields filled with `InputAnalogActionData`; see `InputAnalogActionData_t `_. #### Response Example ```json { "InputAnalogActionData": { "bActive": true, "x": 0.5, "y": 0.2, " சார்பTime": 1678886400 } } ``` ``` -------------------------------- ### ISteamApps - onNewUrlLaunchParameters Source: https://github.com/uspgamedev/luasteam/blob/master/docs/apps.rst Callback function triggered when a new URL launch parameters are received while the game is running. ```APIDOC ## POST /steam/apps/onNewUrlLaunchParameters ### Description Called by Steam when a `steam://run///` URL is navigated to when the game is already running. This callback has no data, use :func:`apps.getLaunchCommandLine` to get the launch parameters from the most recently used URL. ### Method POST ### Endpoint /steam/apps/onNewUrlLaunchParameters ### Parameters #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example { "message": "Callback received." } ``` -------------------------------- ### Handle New URL Launch Parameters (Lua) Source: https://github.com/uspgamedev/luasteam/blob/master/docs/apps.rst Callback function triggered when a 'steam://run///' URL is navigated to while the game is running. Use 'apps.getLaunchCommandLine' to retrieve the parameters. ```Lua -- This is a callback, actual implementation would be within an event handler. -- Example structure: -- Steam.apps.onNewUrlLaunchParameters(function() -- local params = Steam.apps.getLaunchCommandLine() -- -- Process parameters -- end) ``` -------------------------------- ### Get Friends List and Invite Users in Lua Source: https://context7.com/uspgamedev/luasteam/llms.txt Retrieves the player's friends list and allows iterating through it to get friend details like their name. It also includes functionality to invite a friend to a game session using their Steam ID and a connection string. ```lua local steam = require("luasteam") -- Friend flags (can be combined with bitwise OR) local k_EFriendFlagImmediate = 0x04 -- Friends on your list -- Get friend count local friend_count = steam.friends.getFriendCount(k_EFriendFlagImmediate) print("You have", friend_count, "friends") -- Iterate through friends for i = 0, friend_count - 1 do local friend_id = steam.friends.getFriendByIndex(i, k_EFriendFlagImmediate) local friend_name = steam.friends.getFriendPersonaName(friend_id) print("Friend", i + 1, ":", friend_name) end -- Invite friend to game local function invite_friend(friend_id) local success = steam.friends.inviteUserToGame(friend_id, "lobby:12345") if success then print("Invite sent to", steam.friends.getFriendPersonaName(friend_id)) end end ``` -------------------------------- ### Get Device Binding Revision Source: https://github.com/uspgamedev/luasteam/blob/master/docs/input.rst Retrieves the binding revision for a given controller. ```APIDOC ## GET /input/getDeviceBindingRevision ### Description Retrieves the major and minor binding revisions for a controller's Steam Input API configuration. This can be used to check if controller configurations have been updated. ### Method GET ### Endpoint /input/getDeviceBindingRevision ### Parameters #### Path Parameters None #### Query Parameters - **inputHandle** (uint64) - Required - The handle of the controller to query. Obtained from :func:`input.getConnectedControllers`. ### Request Example ``` GET /input/getDeviceBindingRevision?inputHandle=123456789 ``` ### Response #### Success Response (200) - **found** (boolean) - Returns `true` if a device binding was successfully found and `false` if the binding is still loading. - **majorRevision** (number?) - If call was successful, returns the `major` binding revision for Steam Input API configurations. - **minorRevision** (number?) - If call was successful, returns the `minor` binding revision for Steam Input API configurations. #### Response Example ```json { "found": true, "majorRevision": 1, "minorRevision": 2 } ``` ``` -------------------------------- ### ISteamGameServer Callbacks Source: https://github.com/uspgamedev/luasteam/blob/master/docs/game_server.rst List of available callbacks for the ISteamGameServer interface. ```APIDOC ## ISteamGameServer Callbacks ### Description Callbacks that can be triggered by the ISteamGameServer interface. These are typically handled by registering functions to specific events. ### gameServer.onValidateAuthTicketResponse() #### Description Called when a response is received for a validated authentication ticket. ### gameServer.onSteamServersConnected() #### Description Called when the game server successfully connects to Steam servers. ### gameServer.onSteamServersDisconnected() #### Description Called when the game server disconnects from Steam servers. ### gameServer.onSteamServerConnectFailure() #### Description Called when the game server fails to connect to Steam servers. ``` -------------------------------- ### ISteamApps - isDlcInstalled Source: https://github.com/uspgamedev/luasteam/blob/master/docs/apps.rst Checks if a user owns and has a specific DLC installed. ```APIDOC ## GET /steam/apps/isDlcInstalled ### Description Checks if the user owns a specific DLC and if the DLC is installed. ### Method GET ### Endpoint /steam/apps/isDlcInstalled ### Parameters #### Query Parameters - **appID** (number) - Required - The App ID of the DLC to check. #### Request Body None ### Request Example None ### Response #### Success Response (200) - **installed** (boolean) - true if the user owns the DLC and it's currently installed, otherwise false. #### Response Example { "installed": true } ```