luasteam - Lua bindings for the SteamWorks API

luasteam enables you to use SteamWorks API from Lua, for example (but not limited to) when you’re building games with Love2D.

To learn how to use luasteam, check our Getting Started section.

While using this documentation, you may also like to check the SteamWorks API Reference and SteamWorks API Overview.

Getting started

Installation

To install luasteam, you can use one of our pre-compiled binaries in our releases page. Make sure you’re using the same version of this documentation as of the release you downloaded.

Download the correct binary for your platform and rename it to simply luasteam.ext. For example, if you’re using Windows 32-bits, download win32_luasteam.dll and rename it to luasteam.dll. Then copy this file to the same directory as your lua files, and make sure require 'luasteam' works.

Warning

You also need to copy the correct SteamWorks library to the same directory. This library is not on the luasteam repository, and must be downloaded through the SteamWorks website. This version of luasteam is guaranteed to work with SteamWorks SDK v1.42, but probably works with future versions.

After you download the SDK, you should copy the corresponding library for your platform. Here is a cheat-sheet:

  • Linux 32: sdk/redistributable_bin/linux32/libsteam_api.so
  • Linux 64: sdk/redistributable_bin/linux64/libsteam_api.so
  • Windows 32: sdk/redistributable_bin/steam_api.dll
  • Windows 64: sdk/redistributable_bin/win64/steam_api64.dll
  • OSX: sdk/redistributable_bin/osx32/libsteam_api.dylib

Basic Usage

luasteam tries to be very similar to the SteamWorks API, that way you don’t need to learn two different APIs. Big differences (other than lua/C++ differences) are documented.

Initialization and Shutdown

Using the usual SteamWorks API, your code will look like:

#include <steam_api.h>

SteamAPI_Init();
// ...
// when game is closing
SteamAPI_Shudown()

Doing this in luasteam should be as easy as:

local Steam = require 'luasteam'

Steam.init()
-- ...
-- when game is closing
Steam.shutdown()

Check the overview for more info on initialization and shutdown. When developing your game, remember to have Steam turned on and use a steam_appid.txt file.

Normal functions

The lua bindings for normal functions are very similar to the C++ API, so for example

SteamFriends()->ActivateGameOverlay("achievements");

becomes

Steam.friends.activateGameOverlay("achievements")

Callbacks

Callbacks work a little different, for example, the GameOverlayActivated_t callback in ISteamUserFriends can be used creating a function named onGameOverlayActivated inside userStats.

Original code:

class Listener {
    STEAM_CALLBACK(Listener, OnGameOverlayActivated, GameOverlayActivated_t);
};

void Listener::OnGameOverlayActivated(GameOverlayActivated_t* data) {
    if (data->m_bActive)
        printf("Steam overlay now active\n" );
    else
        printf("Steam overlay now inactive\n");
}

Code using luasteam:

function Steam.userStats.onGameOverlayActivated(data)
    if data.active then
        print("Steam overlay now active")
    else
        print("Steam overlay now inactive")
    end
end

CallResults

Using CallResults is also slightly different. Instead of receiving a SteamAPICall_t and registering to listen to it, you simply pass a function as the last argument to the function. This function receives two arguments: data is the object returned by the CallResult and err is a boolean indicating if there was an IO error.

Original code:

class Listener {
public:
    void FindTestLeaderboard(const char *name);

private:
    void OnLeaderboardFindResult(LeaderboardFindResult_t *data, bool err);
    CCallResult<Listener, LeaderboardFindResult_t> leaderboardFindResult;
};

void Listener::OnLeaderboardFindResult(LeaderboardFindResult_t *data, bool err ) {
    if (err || data->m_bLeaderboardFound == 0)
        printf("Leaderboard not found!\n");
    else
        printf("Leaderboard found!\n");
}

// Make the request
void Listener::FindTestLeaderboard() {
    SteamAPICall_t call = SteamUserStats()->FindLeaderboard("test");
    leaderboardFindResult.Set(call, this, &Listener::OnLeaderboardFindResult);
}

Code in luasteam

Steam.userStats.findLeaderboard("test", function(data, err)
    if err or not data.leaderboardFound then
        print("Leaderboard not found!")
    else
        print("Leaderboard found!")
    end
end)

Warning

To use Callbacks and Call Results, you must constantly call Steam.runCallbacks(), preferably in your game loop.

SteamAPI Core Functions

List of Functions

Function Reference

init()
Returns:(boolean) true indicates that all required interfaces have been acquired and are accessible. false indicates one of the following conditions:
  • The Steam client isn’t running. A running Steam client is required to provide implementations of the various Steamworks interfaces.
  • The Steam client couldn’t determine the App ID of game. If you’re running your application from the executable or debugger directly then you must have a steam_appid.txt in your game directory next to the executable, with your app ID in it and nothing else. Steam will look for this file in the current working directory. If you are running your executable from a different directory you may need to relocate the steam_appid.txt file.
  • Your application is not running under the same OS user context as the Steam client, such as a different user or administration access level.
  • Ensure that you own a license for the App ID on the currently active Steam account. Your game must show up in your Steam library.
  • Your App ID is not completely set up, i.e. in Release State: Unavailable, or it’s missing default packages.
SteamWorks:SteamAPI_Init

Initializes the Steamworks API. Must be the first thing you call after loading the library, do it before anything else in your game.

See Initialization and Shutdown for additional information.

Example:

local Steam = require 'luasteam'

if not Steam.init() then
    error("Steam couldn't initialize")
end
shutdown()
Returns:nothing
SteamWorks:SteamAPI_Shutdown

Shuts down the Steamworks API, releases pointers and frees memory.

You should call this during process shutdown if possible.

This will not unhook the Steam Overlay from your game as there’s no guarantee that your rendering API is done using it.

Example:

function onMyGameClosing()
    Steam.shutdown()
end
runCallbacks()
Returns:nothing
SteamWorks:SteamAPI_RunCallbacks

Dispatches callbacks and call results to all of the registered listeners.

It’s best to call this at >10Hz, the more time between calls, the more potential latency between receiving events or results from the Steamworks API. Most games call this once per render-frame. All registered listener functions will be invoked during this call, in the callers thread context.

runCallbacks() is safe to call from multiple threads simultaneously, but if you choose to do this, callback code could be executed on any thread. One alternative is to call runCallbacks() from the main thread only, and call releaseCurrentThreadMemory() (missing) regularly on other threads.

Example:

function myGameLoop(dt)
    Steam.runCallbacks()
end

ISteamFriends

Function Reference

friends.activateGameOverlay(dialog)
Parameters:dialog (string) – The dialog to open. Valid options are: “friends”, “community”, “players”, “settings”, “officialgamegroup”, “stats”, “achievements”.
Returns:nothing
SteamWorks:ActivateGameOverlay

Activates the Steam Overlay to a specific dialog.

Example:

Steam.friends.activateGameOverlay('stats')
friends.activateGameOverlayToWebPage(url)
Parameters:url (string) – The webpage to open. (A fully qualified address with the protocol is required, e.g. “http://www.steampowered.com”)
Returns:nothing
SteamWorks:ActivateGameOverlayToWebPage

Activates Steam Overlay web browser directly to the specified URL.

Example:

Steam.friends.activateGameOverlayToWebPage('https://www.google.com')
friends.getFriendPersonaName(steam_id)
Parameters:steam_id – The Steam ID of the other user.
Returns:(string) The current users persona name. Returns an empty string (“”), or “[unknown]” if the Steam ID is invalid or not known to the caller.
SteamWorks:GetFriendPersonaName

Gets the specified user’s persona (display) name.

This will only be known to the current user if the other user is in their friends list, on the same game server, in a chat room or lobby, or in a small Steam group with the local user.

Example:

steam_id = getSteamIdSomehow()
print("Friend's name is:", Steam.friends.getFriendPersonaName(steam_id))

Callbacks Reference

Warning

Remember callbacks are functions that you should override in order to receive the events, and not call directly.

Also, you must constantly call Steam.runCallbacks() (preferably in your game loop) in order for your callbacks to be called.

friends.onGameOverlayActivated(data)
Parameters:data (table) – A table with a single
Returns:nothing
SteamWorks:GameOverlayActivated_t

Posted when the Steam Overlay activates or deactivates. The game can use this to be pause or resume single player games.

Example:

function Steam.friends.onGameOverlayActivated(data)
    print('Overlay active is', data.active)
end

ISteamUserStats

Function Reference

userStats.getAchievement(name)
Parameters:name (string) – The ‘API Name’ of the achievement.
Returns:(boolean) This function returns true upon success if all of the following conditions are met; otherwise, false.
  • userStats.requestCurrentStats() has completed and successfully returned its callback.
  • The ‘API Name’ of the specified achievement exists in App Admin on the Steamworks website, and the changes are published.
Returns:(boolean?) If the call is successful, returns a second value, the unlock status of the achievement.
SteamWorks:GetAchievement

Gets the unlock status of the Achievement.

The equivalent function for other users is userStats.getUserAchievement() (missing).

Example:

local success, achieved = Steam.userStats.getAchievement('ach_name')
if success and achieved then
    print('Yep, you have the achievement')
end
userStats.setAchievement(name)
Parameters:name (string) – The ‘API Name’ of the Achievement to unlock.
Returns:(boolean) This function returns true upon success if all of the following conditions are met; otherwise, false.
  • The specified achievement ‘API Name’ exists in App Admin on the Steamworks website, and the changes are published.
  • userStats.requestCurrentStats() has completed and successfully returned its callback.
SteamWorks:SetAchievement

Unlocks an achievement.

You must have called userStats.requestCurrentStats() and it needs to return successfully via its callback prior to calling this!

You can unlock an achievement multiple times so you don’t need to worry about only setting achievements that aren’t already set. This call only modifies Steam’s in-memory state so it is quite cheap. To send the unlock status to the server and to trigger the Steam overlay notification you must call userStats.storeStats().

Example:

if achievementConditionSatisfied() and doesntHaveAchievement() then
    Steam.userStats.setAchievement('ach_name')
    Steam.userStats.storeStats() -- shows overlay notification
end
userStats.resetAllStats(achievementsToo)
Parameters:achievementsToo (boolean) – Also reset the user’s achievements?
Returns:(boolean) true indicating success if userStats.requestCurrentStats() has already been called and successfully returned its callback; otherwise false.
SteamWorks:ResetAllStats

Resets the current users stats and, optionally achievements.

This automatically calls userStats.storeStats() to persist the changes to the server. This should typically only be used for testing purposes during development. Ensure that you sync up your stats with the new default values provided by Steam after calling this by calling userStats.requestCurrentStats().

Example:

if dev_mode and keypressed('f10') then
    Steam.userStats.resetAllStats(true)
end
userStats.storeStats()
Returns:(boolen) This function returns true upon success if all of the following conditions are met; otherwise, false.
  • userStats.requestCurrentStats() has completed and successfully returned its callback.
  • The current game has stats associated with it in the Steamworks Partner backend, and those stats are published.
SteamWorks:StoreStats

Send the changed stats and achievements data to the server for permanent storage.

If this fails then nothing is sent to the server. It’s advisable to keep trying until the call is successful.

This call can be rate limited. Call frequency should be on the order of minutes, rather than seconds. You should only be calling this during major state changes such as the end of a round, the map changing, or the user leaving a server. This call is required to display the achievement unlock notification dialog though, so if you have called userStats.setAchievement() then it’s advisable to call this soon after that.

If you have stats or achievements that you have saved locally but haven’t uploaded with this function when your application process ends then this function will automatically be called.

You can find additional debug information written to the %steam_install%\logs\stats_log.txt file.

If the call is successful you will receive a userStats.userStatsStored() callback. If result has a result of “InvalidParam”, then one or more stats uploaded has been rejected, either because they broke constraints or were out of date. In this case the server sends back updated values and the stats should be updated locally to keep in sync.

If one or more achievements has been unlocked then this will also trigger a userStats.userAchievementStored() callback.

Example:

function onMatchEnd()
    Steam.userStats.storeStats()
end
userStats.requestCurrentStats()
Returns:(boolean) Only returns false if there is no user logged in; otherwise, true.
SteamWorks:RequestCurrentStats

Asynchronously request the user’s current stats and achievements from the server.

You must always call this first to get the initial status of stats and achievements. Only after the resulting callback comes back can you start calling the rest of the stats and achievement functions for the current user.

The equivalent function for other users is userStats.requestUserStats() (missing).

Triggers a userStats.userStatsReceived() callback.

Example:

-- before any achievement/stats stuff
Steam.userStats.requestCurrentStats()

function Steam.userStats.userStatsReceived()
    can_do_stats_stuff = true
end
userStats.findLeaderboard(name, callback)
Parameters:
  • name (string) – The name of the leaderboard to find. Must not be longer than 128 bytes.
  • callback (function) – Called asynchronously when this function returns. See below.
Returns:

nothing

SteamWorks:

FindLeaderboard

Gets a leaderboard by name.

You must call either this or userStats.findOrCreateLeaderboard() to obtain the leaderboard handle which is valid for the game session for each leaderboard you wish to access prior to calling any other Leaderboard functions.

callback(data, err) receives two arguments:

  • data (table) – Similar to LeaderboardFindResult_t, or nil if there was err is true.

    • data.steamLeaderboard (leaderboard) – Handle to the leaderboard that was searched for. A special value is returned if no leaderboard was found.
    • data.leaderboardFound (boolean) – Was the leaderboard found? true if it was, false if it wasn’t.
  • err (boolean): true if there was any IO error with the request.

Example:

Steam.userStats.findLeaderboard('l_name', function(data, err)
    if err or not data.leaderboardFound then
        print('Something happened')
    elseif
        uploadScoresHelper(data.steamLeaderboard)
    end
end)
userStats.findOrCreateLeaderboard(name, sortMethod, displayType, callback)
Parameters:
  • name (string) – The name of the leaderboard to find or create. Must not be larger than 128 bytes.
  • sortMethod (string) – The sort order of the new leaderboard if it’s created. Must be ‘Ascending’ or ‘Descending’ (see ELeaderboardSortMethod).
  • displayType (string) – The display type (used by the Steam Community web site) of the new leaderboard if it’s created. Must be one of: ‘Numeric’, ‘TimeSeconds’ or ‘TimeMilliSeconds’ (see ELeaderboardDisplayType).
  • callback (function) – Called asynchronously when this function returns. It must be of the same type as the callback in userStats.findLeaderboard().
Returns:

nothing

SteamWorks:

FindOrCreateLeaderboard

Gets a leaderboard by name, it will create it if it’s not yet created.

You must call either this or userStats.findLeaderboard() to obtain the leaderboard handle which is valid for the game session for each leaderboard you wish to access prior to calling any other Leaderboard functions.

Leaderboards created with this function will not automatically show up in the Steam Community. You must manually set the Community Name field in the App Admin panel of the Steamworks website. As such it’s generally recommended to prefer creating the leaderboards in the App Admin panel on the Steamworks website and using userStats.findLeaderboard() unless you’re expected to have a large amount of dynamically created leaderboards.

Example:

Steam.userStats.findOrCreateLeaderboard('l_name', 'Ascending', 'Numeric', function(data, err)
    if err or not data.leaderboardFound then
        print('Something happened')
    elseif
        uploadScoresHelper(data.steamLeaderboard)
    end
end)
userStats.getLeaderboardName(steamLeaderboard)
Parameters:steamLeaderboard (leaderboard) – A leaderboard handle obtained from userStats.findLeaderboard() or userStats.findOrCreateLeaderboard().
Returns:(string) The name of the leaderboard. Returns an empty string if the leaderboard handle is invalid.
SteamWorks:GetLeaderboardName

Returns the name of a leaderboard handle.

Example:

function printLeaderboardInfo(handle)
    print('Leaderboard name: ' .. Steam.userStats.getLeaderboardName(handle))
    print('Entries: ' .. Steam.userStats.getLeaderboardEntryCount(handle))
    print('Sort Method: ' .. Steam.userStats.getLeaderboardSortMethod(handle))
    print('Display Type: ' .. Steam.userStats.getLeaderboardDisplayType(handle))
end
userStats.getLeaderboardEntryCount(steamLeaderboard)
Parameters:steamLeaderboard (leaderboard) – A leaderboard handle obtained from userStats.findLeaderboard() or userStats.findOrCreateLeaderboard().
Returns:(number) The number of entries in the leaderboard. Returns 0 if the leaderboard handle is invalid.
SteamWorks:GetLeaderboardEntryCount

Returns the total number of entries in a leaderboard.

This is cached on a per leaderboard basis upon the first call to userStats.findLeaderboard() or userStats.findOrCreateLeaderboard() and is refreshed on each successful call to userStats.downloadLeaderboardEntries(), userStats.downloadLeaderboardEntriesForUsers() (missing), and userStats.uploadLeaderboardScore().

Example: See userStats.getLeaderboardName()’s example.

userStats.getLeaderboardSortMethod(steamLeaderboard)
Parameters:steamLeaderboard (leaderboard) – A leaderboard handle obtained from userStats.findLeaderboard() or userStats.findOrCreateLeaderboard().
Returns:(string?) The sort method of the leaderboard, either “Ascending” or “Descending”. Returns nil if the leaderboard handle is invalid.
SteamWorks:GetLeaderboardSortMethod

Returns the sort order of a leaderboard handle.

Example: See userStats.getLeaderboardName()’s example.

userStats.getLeaderboardDisplayType(steamLeaderboard)
Parameters:steamLeaderboard (leaderboard) – A leaderboard handle obtained from userStats.findLeaderboard() or userStats.findOrCreateLeaderboard().
Returns:(string?) The display type of the leaderboard, one of “Numeric”, “TimeSeconds” or “TimeMilliSeconds”. Returns nil if the leaderboard handle is invalid.
SteamWorks:GetLeaderboardDisplayType

Returns the display type of a leaderboard handle.

Example: See userStats.getLeaderboardName()’s example.

userStats.uploadLeaderboardScore(steamLeaderboard, uploadScoreMethod, score, details, callback)
Parameters:
  • steamLeaderboard (leaderboard) – A leaderboard handle obtained from userStats.findLeaderboard() or userStats.findOrCreateLeaderboard().
  • uploadScoreMethod (string) – Do you want to force the score to change, or keep the previous score if it was better? Either “KeepBest” or “ForceUpdate”.
  • score (number) – The score to upload. Must be a 32-bit integer.
  • details (string?) – Optional string with details surrounding the unlocking of this score. Size must be a multiple of four, and at most 256 bytes. Will be converted to an array of 32-bit integers.
  • callback (function) – Called asynchronously when this function returns. See below.
Returns:

nothing

SteamWorks:

UploadLeaderboardScore

Uploads a user score to a specified leaderboard.

Details are optional game-defined information which outlines how the user got that score. For example if it’s a racing style time based leaderboard you could store the timestamps when the player hits each checkpoint. If you have collectibles along the way you could use bit fields as booleans to store the items the player picked up in the playthrough.

Uploading scores to Steam is rate limited to 10 uploads per 10 minutes and you may only have one outstanding call to this function at a time.

callback(data, err) receives two arguments:

  • data (table) – Similar to LeaderboardScoreUploaded_t, or nil if there was err is true.

    • data.success (boolean) – Was the call successful? Returns true if the call was successful, false on failure, for example:

      • The amount of details sent exceeds 256 bytes.
      • The leaderboard is set to “Trusted” in App Admin on Steamworks website, and will only accept scores sent from the Steam Web API.
    • data.steamLeaderboard (leaderboard) – Handle to the leaderboard that was searched for. A special value is returned if no leaderboard was found.

    • data.score (number) – The score that was attempted to set.

    • data.scoreChanged (boolean) – true if the score on the leaderboard changed otherwise false if the existing score was better.

    • data.globalRankNew (number) – The new global rank of the user on this leaderboard.

    • data.globalRankPrevious (number) – The previous global rank of the user on this leaderboard; 0 if the user had no existing entry in the leaderboard.

  • err (boolean): true if there was any IO error with the request.

Example:

function uploadScoresHelper(handle)
    local score = getScore()
    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
userStats.downloadLeaderboardEntries(steamLeaderboard, dataRequest, rangeStart, rangeEnd, callback)
userStats.downloadLeaderboardEntries(steamLeaderboard, dataRequest, callback)
Parameters:
  • steamLeaderboard (leaderboard) – A leaderboard handle obtained from userStats.findLeaderboard() or userStats.findOrCreateLeaderboard().
  • dataRequest (string) – The type of data request to make. Must be one of “Global”, “GlobalAroundUser” or “Friends” (see ELeaderboardDataRequest).
  • rangeStart (number) – The index to start downloading entries relative to dataRequest. Must not be supplied if dataRequest is “Friends”.
  • rangeEnd (number) – The last index to retrieve entries relative to dataRequest. Must not be supplied if dataRequest is “Friends”.
  • callback (function) – Called asynchronously when this function returns. See below.
Returns:

nothing

SteamWorks:

DownloadLeaderboardEntries

Fetches a series of leaderboard entries for a specified leaderboard.

You can ask for more entries than exist, then this will return as many as do exist.

If you want to download entries for an arbitrary set of users, such as all of the users on a server then you can use userStats.downloadLeaderboardEntriesForUsers() (missing) which takes an array of Steam IDs.

callback(data, err) receives two arguments:

  • data (table) – An array of tables similar to LeaderboardEntry_t, or nil if there was err is true.

    • data[i].steamIDUser (steamID) – User who this entry belongs to. You can use friends.getFriendPersonaName() and friends.getSmallFriendAvatar() (missing) to get more info.
    • data[i].globalRank (number) – The global rank of this entry ranging from [1..N], where N is the number of users with an entry in the leaderboard.
    • data[i].score (number) – The raw score as set in the leaderboard.
    • data[i].details (string) – Details of the entry. String is used as a byte array, so may contain a '\0' in the middle.
    • data[i].UGC (ugcHandle) – Handle for the UGC attached to the entry. A special value if there is none. (useless for now, as there are no UGC functions implemented)
  • err (boolean): true if there was any IO error with the request.

Warning

This function has two major differences from the SteamWorks API.

  • If the data request is “Friends”, you must not use the rangeStart and rangeEnd parameters (see the second example).
  • The callback is not called with a table similar to LeaderboardScoresDownloaded_t, and there is no need to use the function GetDownloadedLeaderboardEntry, since this is already done for you. The callback already receives a list of objects like LeaderboardEntry_t.

Examples:

function showGlobalEntries(handle)
    Steam.userStats.downloadLeaderboardEntries(handle, 'Global', 1, 1000, function(data, err)
        if err then
            print('Error happened')
        else
            for _, user in ipairs(data) do
                print('Rank #' .. user.globalRank .. ': ' .. user.score)
            end
        end
    end
end
function showFriendsEntries(handle)
    Steam.userStats.downloadLeaderboardEntries(handle, 'Friends', function(data, err)
        if err then
            print('Error happened')
        else
            for _, user in ipairs(data) do
                local name = Steam.friends.getFriendPersonaName(user.steamIDUser)
                print('Friend ' .. name .. ': ' .. user.score)
            end
        end
    end
end

Indices and tables