Skip to content

Base

These are a loose collection of functions which can be used to perform a variety of actions within Tabletop Simulator.

These functions can utilize in-game Objects, but none of them can be enacted on in-game Objects. They all deal with the game space.

Function Summary

Global Functions

General functions which work within any script.

Function Name Description Return  
addContextMenuItem( label, toRunFunc, keep_open, require_table) Adds a menu item to the Global right-click context menu. Global menu is shown when player right-clicks on empty space or table.
clearContextMenu()
clearContextMenu()
Clears all menu items added by function addContextMenuItem(...).
copy( object_list) Copy a list of Objects to the clipboard. Works with paste(...).
destroyObject( obj) Destroy an Object.
flipTable()
flipTable()
Flip the table.
getAllObjects()
getAllObjects()

Use getObjects().

Returns a Table of all Objects in the game except hand zones.
getObjectFromGUID( guid) Returns Object by its GUID. Will return nil if this GUID doesn't currently exist.
getObjects()
getObjects()
Returns a Table of all Objects in the game.
getObjectsWithTag( tag) Returns Table of all Objects which have the specified tag attached.
getObjectsWithAnyTags( tags) Returns Table of all Objects which have at least one of the specified tags attached.
getObjectsWithAllTags( tags) Returns Table of all Objects which have all of the specified tags attached.
getSeatedPlayers()
getSeatedPlayers()
Returns a Table of the Player Colors strings of seated players.
group( objects) Groups objects together, like how the G key does for players.
paste( parameters) Pastes Objects in-game that were copied to the in-game clipboard. Works with copy(...).
setLookingForPlayers(
setLookingForPlayers(...)
lfp)
Enables/disables looking for group. This is visible in the server browsers, indicating if you are recruiting for a game.
spawnObject( parameters) Spawns an object.
spawnObjectData( parameters) Spawns an object from a data table.
spawnObjectJSON( parameters) Spawns an object from a JSON string.
startLuaCoroutine( function_owner, function_name) Start a coroutine.
stringColorToRGB( player_color) Converts a Player Color string into a Color Table for tinting.

Hotkey Functions

Function Name Description Return  
addHotkey( label, toRunFunc, trigger_on_key_up) Adds a bindable hotkey to the game.
clearHotkeys()
clearHotkeys()
Clears all hotkeys previously added via addHotkey(...).
showHotkeyConfig()
showHotkeyConfig()
Shows the hotkey configuration window under Options->Game Keys.

Message Functions

Functions which handle sending and displaying data.

Function Name Description Return  
broadcastToAll( message, message_tint) Print an on-screen message to all Players, as well as their in-game chat.
broadcastToColor( message, player_color, message_tint) Print an on-screen message to a specified Player, as well as their in-game chat.
log( value, label, tags) Logs a message to the host's System Console. (Shortcut: ~)
logString( value, label, tags, concise, displayTag) Returns a String formatted similarly to the output of log(...).
logStyle( tag, tint, prefix, postfix) Set style options for the specified tag type for the log.
print( message) Prints a string into chat that only the host is able to see. Used for debugging scripts.
printToAll( message, message_tint) Print a message into the chat of all connected players.
printToColor( message, player_color, message_tint) Print a message to a specific Player Color.
sendExternalMessage(
sendExternalMessage(...)
data)
Send a table to your external script editor, most likely Atom. This is for custom editor functionality.

Function Details

Global Function Details

addContextMenuItem(...)

Adds a menu item to the Global right-click context menu. Global menu is shown when player right-clicks on empty space or table.

addContextMenuItem(label, toRunFunc, keep_open, require_table)

  • label: Label for the menu item.
  • toRunFunc: Execute if menu item is selected.
    • player_color Player Color who selected the menu item.
    • menu_position Global position of the right-click context menu.
  • keep_open: Keep context menu open after menu item was selected.
    • Optional, Default: keep_open = false. Close context menu after selection.
  • require_table: Show added menu item when right-clicked on empty space or table.
    • Optional, Default: require_table = false. Show when right-clicked on empty space or table
function onLoad()
    addContextMenuItem("doStuff", itemAction)
end

function itemAction(player_color, menu_position)
    print(player_color)
end

copy(...)

Copy a list of Objects to the clipboard. Works with paste(...).

copy(object_list)

  • object_list: A Table of in-game objects to be copied.
    • This is similar to highlighting the objects in-game and copying them.
object_list = {
    getObjectFromGUID("######"),
    getObjectFromGUID("######"),
}
copy(object_list)

destroyObject(...)

Destroy an Object.

destroyObject(obj)

  • obj: The Object you wish to delete from the instance.

getObjectFromGUID(...)

Returns Object by its GUID. Will return nil if this GUID doesn't currently exist.

getObjectFromGUID(guid)

  • guid: GUID of the Object to get a reference of.
    • GUID can be obtained by right clicking an object and going to Scripting.
    • In a script, it can be obtained from any Object by using .getGUID().

group(...)

Groups objects together, like how the G key does for players. It returns a table of object references to any decks/stacks formed.

Not all objects CAN be grouped. If the G key won't work on them, neither will this function.

group(objects)

  • objects: A list of objects to be grouped together.

Format of the returned table

  • A table containing the grouped objects, numerically indexed.
    • Object(s)
      • Different types of object are grouped independently i.e. cards will form into a deck, each type of checker will form their own stack.

-- Example
function onLoad()
    local objects = {
        -- IMPORTANT: To get the example to work, you need to replace ###### by a real GUID of the object.
        getObjectFromGUID("######"), -- card
        getObjectFromGUID("######"), -- card
        getObjectFromGUID("######"), -- checker
        getObjectFromGUID("######"), -- checker
    }
    local objGroupedList = group(objects)
    log(objGroupedList)
end
-- Possible Output for objGroupedList
{
    1: <Deck>
    2: <CheckerStack>
}


paste(...)

Pastes Objects in-game that were copied to the in-game clipboard. Works with copy(...).

paste(parameters)

  • parameters: A Table containing instructions of where to spawn the Objects.
    • parameters.position: Position of the first object to paste.
      • Optional, defaults to {0, 3, 0}.
    • parameters.snap_to_grid: If snap-to-grid is active on the spawned item/s.
      • Optional, defaults to false (off).

spawnObject(...)

Spawns an object.

Refer to the spawnable Built-in Object and Custom Object pages for details about the types of objects that can be spawned.

If you are spawning a Custom Object, you should immediately call setCustomObject(...) on the object returned from spawnObject(...).

spawnObject(parameters)

Spawn Parameters

parameters must be provided as a table, which may have the following properties:

Name Type Default Description
type Mandatory Built-in or Custom Game Object name.
position {0, 0, 0} Position where the object will be spawned.
rotation {0, 0, 0} Rotation of the spawned object.
scale {1, 1, 1} Scale of the spawned object.
sound true Whether a sound will be played as the object spawns.
snap_to_grid false Whether upon spawning, the object will snap to nearby grid lines (or snap points).
callback_function nil Called when the object has finished spawning. The spawned object will be passed as the first and only parameter.

type is mandatory, all other properties are optional. When a property is omitted, it will be given the corresponding default value (above).

Objects take a moment to spawn. The purpose of callback_function is to allow you to execute additional code after the object has finished spawning.

Example

Spawn (with sound disabled) a 2x scale "RPG Bear" object in the center of the table and initiate a smooth move on the object. Once the object has finished spawning, log the object's bounds.

local object = spawnObject({
    type = "rpg_BEAR",
    position = {0, 3, 0},
    scale = {2, 2, 2},
    sound = false,
    callback_function = function(spawned_object)
        log(spawned_object.getBounds())
    end
})
object.setPositionSmooth({10, 5, 10})


spawnObjectData(...)

Spawns an object from an object data table representation.

This API gives you complete control over all persistent properties that an object has.

spawnObjectData(parameters)

Spawn Parameters

parameters must be provided as a table, which may have the following properties:

Name Type Default Description
data Mandatory

Table with properties describing the object that will be spawned.

Required content depends on the type of object being spawned.

position nil Position where the object will be spawned. When specified, overrides the Transform position in data.
rotation nil Rotation of the spawned object. When specified, overrides the Transform rotation in data.
scale nil Scale of the spawned object. When specified, overrides the Transform scale in data.
callback_function nil Called when the object has finished spawning. The spawned object will be passed as the first and only parameter.

data is mandatory, all other properties are optional. When a property is omitted, it will be given the corresponding default value (above).

Objects take a moment to spawn. The purpose of callback_function is to allow you to execute additional code after the object has finished spawning.

Tip

You can derive your data table from another object by calling getData() on it, and manipulating the resultant table as you see fit.

Example

Spawn a 2x scale "RPG Bear" object with a blue base in the center of the table and initiate a smooth move on the object. Once the object has finished spawning, log the object's bounds.

local object = spawnObjectData({
    data = {
        Name = "rpg_BEAR",
        Transform = {
            posX = 0,
            posY = 3,
            posZ = 0,
            rotX = 0,
            rotY = 180,
            rotZ = 0,
            scaleX = 2,
            scaleY = 2,
            scaleZ = 2
        },
        ColorDiffuse = {
            r = 0.3,
            g = 0.5,
            b = 0.8
        }
    },
    callback_function = function(spawned_object)
        log(spawned_object.getBounds())
    end
})
object.setPositionSmooth({10, 5, 10})


spawnObjectJSON(...)

Spawns an object from a JSON string.

This API gives you complete control over all persistent properties that an object has.

Tip

Unless you've already got an object's JSON representation at your disposal then spawnObjectData(...) is the preferred API as it's less resource intensive.

spawnObjectJSON(parameters)

Spawn Parameters

parameters must be provided as a table, which may have the following properties:

Name Type Default Description
json Mandatory

JSON string describing the object that will be spawned.

Required content depends on the type of object being spawned.

position nil Position where the object will be spawned. When specified, overrides the Transform position in json.
rotation nil Rotation of the spawned object. When specified, overrides the Transform rotation in json.
scale nil Scale of the spawned object. When specified, overrides the Transform scale in json.
callback_function nil Called when the object has finished spawning. The spawned object will be passed as the first and only parameter.

json is mandatory, all other properties are optional. When a property is omitted, it will be given the corresponding default value (above).

Objects take a moment to spawn. The purpose of callback_function is to allow you to execute additional code after the object has finished spawning.

Example

Spawn a 2x scale "RPG Bear" object with a blue base in the center of the table and initiate a smooth move on the object. Once the object has finished spawning, log the object's bounds.

local object = spawnObjectJSON({
    json = [[{
        "Name": "rpg_BEAR",
        "Transform": {
            "posX": 0,
            "posY": 3,
            "posZ": 0,
            "rotX": 0,
            "rotY": 180,
            "rotZ": 0,
            "scaleX": 2,
            "scaleY": 2,
            "scaleZ": 2
        },
        "ColorDiffuse": {
            "r": 0.3,
            "g": 0.5,
            "b": 0.8
        }
    }]],
    callback_function = function(spawned_object)
        log(spawned_object.getBounds())
    end
})
object.setPositionSmooth({10, 5, 10})
The [[...]] syntax above denotes a multi-line string.


startLuaCoroutine(...)

Start a coroutine. A coroutine is similar to a function, but has the unique ability to have its run paused until the next frame of the game using coroutine.yield(0).

Attention

You MUST return a 1 at the end of any coroutine or it will throw an error.

startLuaCoroutine(function_owner, function_name)

  • function_owner: The Object that the function being called is on. Global is a valid target.
  • function_name: Name of the function being called as a coroutine.
function onLoad()
    startLuaCoroutine(Global, "print_coroutine")
end

-- Prints a message, waits 250 frames, prints another message
function print_coroutine()
    print("Routine has Started")
    count = 0
    while count < 250 do
        count = count + 1
        coroutine.yield(0)
    end

    print("Routine has Finished")

    return 1
end

stringColorToRGB(...)

Converts a Player Color string into a Color Table for tinting.

stringColorToRGB(player_color)

printToAll("Blue message", stringColorToRGB("Blue"))

Hotkey Function Details

addHotkey(...)

Adds a bindable hotkey to the game.

Players can bind key to hotkeys from the Options -> Game Keys UI after this function is called.

Important

Added hotkeys are unable to persist between loads/rewinds, because the bound callback function may no longer exist. Therefore addHotkey(...) needs to be called each time the game is loaded. As long as the same labels are used, then player hotkey bindings will persist.

addHotkey(label, callback, triggerOnKeyUp)

  • label: A label displayed to users.
  • callback(playerColor, hoveredObject, pointerPosition, isKeyUp): The function that will be executed whenever the hotkey is pressed, and also when released if triggerOnKeyUp is true.
    • playerColor: Player Color of the player that pressed the hotkey.
    • hoveredObject: The object that the Player's pointer was hovering over at the moment the key was pressed/released. nil if no object was under the Player's pointer at the time.
    • pointerPosition: Word Position of the Player's pointer at the moment the key was pressed/released.
    • isKeyUp: Whether this callback is being triggered in response to a hotkey being released.
  • triggerOnKeyUp: Whether the callback is also executed when the hotkey is released. The callback is always triggered when the hotkey is pressed.
    • Optional, defaults to false.

Hotkey bindings do not prevent the behavior of Settings key bindings i.e. if R (shuffle by default) is assigned as a hotkey, the hotkey callback and the default shuffle behavior will both be executed whenever R is pressed.

Example

addHotkey("My Hotkey", function(playerColor, object, pointerPosition, isKeyUp)
    local action = isKeyUp and "released" or "pressed"
    print(playerColor .. " " .. action .. " the hotkey")
end, true)

Message Function Details

broadcastToAll(...)

Print an on-screen message to all Players.

broadcastToAll(message, message_tint)

  • message: Message to display on-screen.
  • message_tint: A Table containing the RGB color tint for the text.
msg = "Hello all."
rgb = {r=1, g=0, b=0}
broadcastToAll(msg, rgb)

broadcastToColor(...)

Print an on-screen message to a specified Player and their in-game chat.

broadcastToColor(message, player_color, message_tint)

  • message: Message to display on-screen.
  • player_color: Player Color to receive the message.
  • message_tint: RGB color tint for the text.
msg = "Hello White."
color = "White"
rgb = {r=1, g=0, b=0}
broadcastToColor(msg, color, rgb)

log(...)

Logs a message to the host's System Console (accessible from ~ pane of in-game chat window).

log(value, label, tags)

  • value: The value you want to log.
  • label: Text to be logged before value.
    • Optional, defaults to an empty String. Empty Strings are not displayed.
  • tags: The log tag/style or a space separated list of log tags/styles. (See: logStyle(...))
    • Optional, defaults to logging with the <default> log style.

If value is not already a , then it will be converted to a human-readable representation.

If value is a , then the table's contents (keys & values) will be displayed. The contents of nested tables will also be displayed up to a user-configurable depth.

Tip

Table contents max depth is configurable via the log_max_table_depth System Console command.

As an advanced feature, multiple log tags may be provided by space-separating several tags (in the one String) provided as the tags parameter. The message style will be taken from the first tag that the user has not explicitly disabled.

Example

Log a simple message:

log("Something happened")

Example

Log a table (of objects):

log(getObjects())

Example

Log a message with a label and using the "error" log style:

log("Something unexpected happened.", "Oh no!", "error")


logString(...)

Returns a String formatted similarly to the output of log(...).

logString(value, label, tags, concise, displayTag)

  • value: The value you want to log.
  • label: Text to be logged before value.
    • Optional, defaults to an empty String. Empty Strings are not displayed.
  • tags: The log tag/style or a space separated list of log tags/styles.
    • Optional, defaults to logging without any tags.
  • concise: Whether the resultant String should be generated in a more compact form (less newline characters).
    • Optional, defaults to `false`.
  • displayTag: Whether the specified tag(s) should be included as prefix of the resultant String.
    • Optional, defaults to `false`.

If value is not already a , then it will be converted to a human-readable representation.

If value is a , then the table's contents (keys & values) will be included in the resultant String. The contents of nested tables will also be displayed up to a user-configurable depth.

Tip

Table contents max depth is configurable via the log_max_table_depth System Console command.

In some circumstances log strings have newlines inserted e.g. between the label and the textual representation of value. Providing true as the value for concise will use space separators instead of newlines.

Example

Print, as opposed to log, the contents of a table (of objects):

print(logString(getObjects()))


logStyle(...)

Configures style options for a log(...) tag.

Tip

Tag log styles can also be set via the System Console with the log_style_tag command.

logStyle(tag, tint, prefix, postfix)

  • tag: A String of the log's tag.
  • tint: RGB value to tint the log entry's text.
    • String color will also work. Example: "Red"
  • prefix: Text to place before this type of log entry.
    • Optional, defaults to an empty String. Empty Strings are not displayed.
  • postfix: Text to place after this type of log entry.
    • Optional, defaults to an empty String. Empty Strings are not displayed.

Example

Sets the log style (grey text and a suffix) for the log tag "seats". Then proceeds to log a table of available seat colors, using this tag/style.

logStyle("seats", {0.5, 0.5, 0.5}, "", "End List")
log(Player.getAvailableColors(), nil, "seats")


print(...)

Print a string into chat that only the host is able to see. Used for debugging scripts.

print(message)

  • message: Text to print into the chat log.

printToAll(...)

Print a message into the in-game chat of all connected players.

printToAll(message, message_tint)

  • message: Message to place into players' in-game chats.
  • message_tint: RGB values for the text's color tint.
printToAll("Hello World!", {r=1,g=0,b=0})

printToColor(...)

Print a message to the in-game chat of a specific player.

printToColor(message, player_color, message_tint)

  • message: Message to place into the player's in-game chat.
  • player_color: Player Color of the player that will receive the message.
  • message_tint: RGB values for the text's color tint.
printToColor("Hello Red.", "Red", {r=1,g=0,b=0})