Rooms How-to

💡Getting started with programming in Rooms?
Check out the tutorial and the overview video to get started, and join us on discord if you have questions!

📚 Table of Contents

✍ Introduction
โœจ Effects
๐Ÿ  Room
  • reset - Reset room to its pristine state. Everything will go back to the original
  • goToRoom - Goes to another room. This can be used to make objects "links" to other
  • setRoomLighting - Set room light preset.
  • isOwnRoom - Determines if this is a room owned by the current user. For example, if you
๐Ÿง  Logic
  • wait - Runs the given function after waiting for the given time (in seconds).
  • every - Runs the given function periodically.
๐Ÿ’ฌ Communication
  • send - Sends a message to a specific thing.
  • broadcast - Broadcasts a message to all things in the room.
๐Ÿ› ๏ธ Utilities
  • print - Displays a short message on the screen. The message will be visible
  • openUrl - Opens a given url in a new tab in the browser, or in the default
  • randomPick - Returns a random element of the given array.
  • unixTime - Returns the current time in seconds since epoch. This is also known
  • dateTime - Gets the current date and time as a standard ISO string. For example,
  • roomTime - Gets the current "room time", that is the number of seconds elapsed since
  • insert - Adds an element to the end of an array. If you want to insert
  • insertAt - Adds an element to the specified index of an array,
  • remove - Removes an element from an array.
  • openCamera - Opens a camera from the pespective of the current thing.
๐Ÿ’ผ Session
๐Ÿค– AI
  • aiCharacter - All-in-one AI conversation function. It's recommended that you call this
  • aiChatCreate - Creates a new AI conversation. This won't actually cause the AI to answer; this only
  • aiChat - Continues an AI conversation by providing user input.
โž• Math
  • distance - Calculates the distance between two points in 3D space.
  • min - Returns the smallest of two numbers.
  • max - Returns the biggest of two numbers.
  • abs - Returns the absolute value of a number.
  • floor - Returns the floor of a number, that is, the greatest integer
  • ceil - Returns the ceiling of a number, that is, the smallest integer
  • round - Rounds a number to the nearest integer.
  • sin - Returns the sine of an angle given in degrees.
  • cos - Returns the cosine of an angle given in degrees.
  • tan - Returns the tangent of an angle given in degrees.
  • random - Returns a random integer number between 1 and max.
  • randomBetween - Returns a random integer number in the given interval.
  • randomFloat - Returns a random floating-point number between 0 and 1,
  • randomSeed - Sets the random number seed.
๐Ÿงต Strings
  • toLowercase - Converts a string into lowercase.
  • toUppercase - Converts a string into uppercase.
  • substring - Returns a substring (piece) of a string.
  • find - Finds a pattern in a string.
  • split - Splits a string using a given delimiter.
  • join - Joins an array of strings into a single string using the
  • replaceAll - Replaces all occurences of the given pattern in the given string,
๐Ÿ“ท Photo
  • sharePhoto - Shows the user a photo so they can share it.
  • instantPhoto - Takes a photo from the current perspective of the Thing and opens up
  • takePhoto - Takes a photo from the current perspective of the Thing and returns
๐Ÿ“” Comments
  • fetchComments - Fetches the comments for the current room. Comments are text or images that other
  • promptForComment - Prompts the user for a (text) comment to send to the room. The user will have
๐ŸŽฎ High Scores
  • loadHighScores - Gets a list of high scores for the current room.
  • submitHighScore - Submits a high score for the current user for the current room.
  • deleteHighScore - Deletes the high score for the current user for the current room.
๐Ÿฆ„ Thing
  • getThing - Gets a thing by name.
  • getAllThings - Gets a list of all the Things in the room.
  • say - Shows a speech bubble.
  • getPosition - Gets the thing's position.
  • getLocalPosition - (Advanced) Gets the thing's LOCAL position.
  • getRotation - Gets the thing's rotation.
  • getLocalRotation - (Advanced) Gets the thing's LOCAL rotation.
  • setPosition - Sets the thing's position instantaneously. If you want to animate it instead
  • setLocalPosition - (Advanced) Sets the thing's LOCAL position instantaneously. The local position is the
  • setRotation - Sets the thing's rotation instantaneously.
  • setLocalRotation - (Advanced) Sets the thing's local rotation instantaneously. This sets the rotation of
  • getCenter - Gets the position of this thing's center (x, y, z).
  • getName - Gets a thing's name.
  • setTint - Sets this Thing's tint color.
  • getTint - Gets the Thing's tint color as a hex string.
  • startMoveTo - Moves smoothly to a given position (animating). This will animate the
  • stopMove - Stops a "move" animation on the Thing. This stops the animation previously
  • setVelocity - Sets a Thing's velocity directly. Note that this is INCOMPATIBLE with
  • setSpin - Sets a Thing's angular velocity directly. Note that this is INCOMPATIBLE with
  • getVelocity - Gets the Thing's current velocity. This only works for Things that have a physics type
  • getSpin - Gets the Thing's current angular velocity (spin speed). This only works for Things
  • startSpin - Starts spinning.
  • stopSpin - Stops a "spin" animation on the Thing. This stops the animation previously
  • startMoveBy - Moves smoothly by a given delta (animating). This will animate the
  • startBounce - Starts a "bounce" animation on the Thing. This animation will make it
  • stopBounce - Stops a "bounce" animation on the Thing. This stops the animation previously
  • startSway - Starts a sway motion (tilting to one side and then the other repeatedly).
  • stopSway - Stops a sway motion previously started with startSway.
  • startSwivel - Starts a swivel motion (turning from side to side repeatedly).
  • stopSwivel - Stops a swivel motion previously started with startSwivel.
  • startBackAndForth - Starts a back and forth motion.
  • stopBackAndForth - Stops a back and forth motion previously started with startBackAndForth.
  • startUpAndDown - Starts an up and down motion.
  • stopUpAndDown - Stops an up-and-down motion previously started with startUpAndDown.
  • applyForce - Applies a physical force on this Thing in the given force direction. Note
  • setText - Sets the text of the Thing. This only works for Things that can have text
  • setMedia - Sets a new media on the Thing. This only works for Things that can have
  • getMedia - Gets the media of a Thing. This only works for Things that can have
  • enableLight - Enable/disable a Thing's light. This only works for Things that are light
  • disableLight - Disable a Thing's light.
  • getCloudString - Gets a string value from the Thing's cloud memory.
  • setCloudString - Sets a string value on the Thing's cloud memory. It can later be read
  • getCloudInt - Gets an integer value from the Thing's cloud memory.
  • setCloudInt - Sets an integer value on the Thing's cloud memory. It can later be read
  • addToCloudInt - Adds a number to a value on the Thing's cloud memory. It can later be read
  • setPhysicsType - Sets the Thing's physics behavior.
  • isKinematic - Returns true if this thing is KINEMATIC, false if DYNAMIC.
  • isDynamic - Returns true if this thing is DYNAMIC, false if KINEMATIC.
  • getPhysicsType - Returns the Thing's physics type.
  • getForwardDir - Returns the thing's forward direction. This is the direction of the Thing's
  • getRightDir - Returns the thing's 'right' direction. This is the direction of the Thing's
  • getUpDir - Returns the thing's 'up' direction. This is the direction of the Thing's
  • getBackDir - The opposite of getForwardDir.
  • getLeftDir - The opposite of getRightDir.
  • getDownDir - The opposite of getUpDir.
  • setFrame - Sets this thing's animation frame number. This will cause the Thing to stop playing its
  • setAnimation - Sets this thing's animation parameters. This overrides setFrame.
  • getParent - Gets the Thing's parent.
  • getChild - Gets a child by name.
  • getChildren - Gets a list of all the Things that are children of the current thing.
  • getDescendants - Gets a list of all the Things that are descendants of the current thing,
  • prompt - Asks the user to input some text.
  • requestClone - (Advanced!) Requests that the thing be cloned, that is, creates a new thing
  • requestDelete - Requests that a Thing be deleted. It will only be deleted at runtime (while in Play/Preview mode),
  • getOpacity - Gets the Thing's current opacity value.
  • setOpacity - Sets the Thing's current opacity value.
  • setScale - Sets the Thing's current scale.
  • getScale - Gets the Thing's current scale.
๐ŸŽž๏ธ Video

✍ Introduction

This is the documentation for the scripting API used in rooms.xyz. If you are new to this API, the best way to get started is with the tutorial.

A room is made up of objects, called Things. Each Thing can have a script, which is a snippet of Lua code that tells it how to behave, how to react to user interactions, etc.

The script is programmed in Lua, a commonly used scripting language. Note, however, that not all Lua features and libraries work on Rooms.

A script has functions that are called when certain things happen. As a script writer, you implemement these functions to tell the Thing what to do. For example, the onClick function is called by the engine when the user clicks on a Thing, so if you write an onClick function on your Thing, then the contents of that function will execute whenever it's clicked.

An example:

function onClick()
  say("Hello")
end

In this example, whenever you click on the Thing, it will show a speech bubble saying "Hello".

Things and Thing Methods

Some API functions are methods. A method, in Object Oriented Programming means a function that can be called on an object. For our purposes, it means that they can be called on a particular Thing.

For example, say is a Thing method, so it can be called on other Things to make them say something. For example, imagine we a room with three characters in it: Jason, Nick and Bruno, and a button at the center. Here is an example script for the button:

function onClick()
  local jason = getThing("Jason")
  jason:say("Hello, I'm Jason")

  local nick = getThing("Nick")
  nick:say("Hello, I'm Nick")

  local bruno = getThing("Bruno")
  bruno:say("Hello, I'm Bruno")
end
  

So, in this case, when that button is clicked, each of the three characters in the room would introduce themselves.

Not all functions are methods. In this documentation, they will be clearly marked as such.

Special Functions (Handlers)

Some function names are special and will automatically be called by the engine under certain circumstances. These are also called "handlers" because they handle a certain event. These are:

Handling Input

There are 6 buttons that the user can press: "up", "down", "left", "right", "a" and "b". These are on-screen buttons on mobile devices, and correspond to keys on the keyboard when the user is on a desktop.

To use these buttons, you can use the onButtonDown and onButtonUp functions explained above, or query their state directly through the input special table. The input global table contains the following members:

In addition, if you want to find out if the user just pressed or just released a button, all of these have corresponding variables that tell you that, for example, for the "up" button these would be:

In addition, you can read the state of the DPAD in a more practical way by querying the direction that it encodes, rather than reading individual buttons:

Here is an example of moving a character with the DPAD and setting its orientation towards where it's moving.

function onUpdate()
  -- Move character in the direction of the DPAD with speed 5.
  setVelocity(input.natX * 5, input.natZ * 5)
  -- Rotate character to face direction of movement.
  setRotation(0, input.natYaw, 0)
end
  

Physics types

Every thing has a specified Physics type. These are the 5 options:

Shortcuts

Rooms offers a variety of shortcuts to speed up the editing process for advanced users.

Room Editor

Model Editor

Play mode

Camera Mode

The rest of this document is a list of all the functions and methods available to you. Have fun scripting!

โœจ Effects

playSound

playSound(soundFileName, loop, volume, delayBeforeStart)

Plays a sound effect.

soundFileName (string)

The name of the sound effect to play. The extension (".wav" or ".mp3") is optional.

loop (boolean) - optional

If true, the sound will loop. If false, it will play only once.

volume (number) - optional

How loud to play from 0 - 1.

delayBeforeStart (number) - optional

How long to wait before playing, in seconds.

-- Play a sound once.
playSound("click.wav")
-- Play a looping sound.
playSound("music.wav", true)

playSoundWithPitch

playSoundWithPitch(soundFileName, pitch, volume)

Plays a sound effect with pitch (similar to playSound).

soundFileName (string)

The name of the sound effect to play.

pitch (number)

The pitch to use. This is in musical semitones above the normal pitch, so if the normal sound is a C note, then pitch 1 would be C#, pitch 2 would be D, etc. Likewise, -1 would be B on the octave below.

volume (number) - optional

How loud to play from 0 - 1.

-- Play the note in its natural pitch.
playSoundWithPitch("note.wav", 0)
-- Play the same note 3 semitones higher, half volume.
playSoundWithPitch("note.wav", 3, 0.5)
-- Play the same note 2 semitones lower.
playSoundWithPitch("note.wav", -2)

setSoundVolume

setSoundVolume(soundFileName, volume)

Sets volume on any active sounds in the room with the given name, previously started with playSound or playSoundWithPitch. Note: Does not set volume for future sounds of the same name

soundFileName (string)

The name of the sound effect that will change volume.

-- Set coin collect sound volume.
setSoundVolume("coin.wav", 0.5)

stopSound

stopSound(soundFileName)

Stops a sound effect that was previously started with playSound or playSoundWithPitch.

soundFileName (string)

The name of the sound effect to stop.

-- Stop playing music.
stopSound("music.wav")

explode

explode(x, y, z, radius, force)

Applies an explosion force centered on a given position and with a given radius and intensity. This will only affect objects that have physics enabled.

x, y, z (number)

The position of the center of the explosion.

radius (number) - optional

The radius of the explosion (it's a sphere around the center). If not specified, this defaults to 100.

force (number) - optional

This is the force (intensity) of the explosion. If not specified, this defaults to 10000.

function onClick()
  -- Get my position.
  local x, y, z = getPosition()
  -- Play an explosion sound effect.
  playSound("kaboom.wav")
  -- Apply the explosion force.
  explode(x, y, z)
end

particles

Thing:particles(particlesName, options)

Launches particle effect.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

particlesName (string)

The name of the particle effect to launch. This can be: "explosion", "faucet", "flame", "plasma", "puff", "rain" "smoke", "snow", "steam", "waterfall".

options (table) - optional

If provided, this is a table with additional particle effect configuration options. See the advanced section below for more information.

This returns a particle effect ID that you can later use to stop the particle effect with stopParticles if you want.

-- Launch a puff effect at my position.
particles("puff")
-- Launch a puff effect 10 units above me.
particles("puff", {ly=10})
-- Launch a green puff effect 10 units above me.
particles("puff", {ly=10, color="#00ff00"})
-- Launch a waterfall effect. Note that this one is continuous
-- so you need to stop it with stopParticles if you want it to end.
particles("waterfall")
-- Launch a waterfall effect, but just for 10 seconds.
particles("waterfall", {duration=10})
-- Launch a waterfall effect, but rotated by 90 degrees.
particles("waterfall", {ry=90})

Advanced ▾
These are the possible parameters in the options table:
  • x, y, z: the world position of the effect.
  • lx, ly, lz: the local position of the effect (offset from the Thing). Can't be used together with x, y, z.
  • rx, ry, rz: local rotation of the effect.
  • color: color of the effect. This is a hex string like "#ff0000" for red.
  • startColor, endColor: Start and end color of the particles. This can't be used with color.
  • density: Relative density of effect. 1 is the default. For example, 2 would be twice as many particles.
  • duration: Duration of the effect in seconds. Can only be used with continuous effects like flame, rain, smoke, etc, not with instantaneous effects like explosions.
  • scale: Scale factor to apply to the whole effect to make it bigger or smaller.
  • scaleX,scaleY,scaleZ: scale factor but specified individually per axis. Can't be used with scale.
  • escale: escale factor to apply to the emitter region of the effect to make it bigger or smaller.
  • escaleX,escaleY,escaleZ: escale factor but specified individually per axis. Can't be used with escale.

stopParticles

Thing:stopParticles(particlesId)

Stops a particle effect.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

particlesId (string)

The ID of the particle effect to stop, received from a call to particles.

partId = nil
-- Start/stop the flame with the user clicks it.
function onClick()
  if partId then
    -- Flame is active, so stop it using its ID.
    stopParticles(partId)
    partId = nil
  else
    -- Start the flame and store its ID.
    partId = particles("flame")
  end
end

๐Ÿ  Room

reset

reset()

Reset room to its pristine state. Everything will go back to the original state. Any scheduled function calls (via wait or every, for example) will be cancelled.

reset()

goToRoom

goToRoom(roomName, keepSession)

Goes to another room. This can be used to make objects "links" to other rooms so that when the user clicks on them, they are transported.

roomName (string)

The name of the room to go to.

keepSession (boolean) - optional

If true, session values set with setSessionValue are passed on to the next room. This can be useful when making multi-room experiences. This ONLY works if the room belongs to the same owner as the current one! If omitted, this defaults to false.

function onClick()
  -- Go to the room called 'space' by user 'jason'.
  goToRoom("jason/space")
end

setRoomLighting

setRoomLighting(roomLightingPreset)

Set room light preset.

roomLightingPreset (string)

The light preset to use. This can be "BRIGHT", "DIM" or "DARK".

-- Light switch that toggles between BRIGHT and DIM lighting.
isOn = true
function onClick()
  -- Invert the value of isOn
  isOn = not isOn
  -- Set the room lighting
  if isOn then
    setRoomLighting("BRIGHT")
  else
    setRoomLighting("DIM")
  end
end
setRoomLighting("DARK")

isOwnRoom

isOwnRoom()

Determines if this is a room owned by the current user. For example, if you are user "foo" and the room is "foo/bowling", then you are the owner of the room. If you are "foo" and you are in room "bar/tennis", then you are not the owner of the room

This is useful to enable debug settings for yourself on your own room, but not for other people who visit.

function onStart()
  if isOwnRoom() then
    -- enable some debug stuff
  end
end

๐Ÿง  Logic

wait

wait(delayInSeconds, functionToCall)

Runs the given function after waiting for the given time (in seconds).

delayInSeconds (number)

How long to wait before running the function, in seconds.

functionToCall (function)

The function to call after the given delay.

function onClick()
  -- Say 'hello', wait 3 seconds and say 'How are you?'
  say("Hello.")
  wait(3, myOtherFunction)
end

function myOtherFunction() say("How are you?") end

every

every(intervalInSeconds, functionToCall)

Runs the given function periodically.

intervalInSeconds (number)

The interval between successive calls of the given function.

functionToCall (function)

The function to call periodically.

-- This example will count up: 0, 1, 2, 3, 4, ...
function onStart()
  -- Every 2 seconds, run countUp.
  every(2, countUp)
end

count = 0 function countUp() count = count + 1 say(count) end

๐Ÿ’ฌ Communication

send

send(target, name, args, delay)

Sends a message to a specific thing.

How does this work? Let's say you send the message "Hello" to a thing. Then that thing will receive a call to its "onHello()" function in its script. The name of the function called is always "on" followed by the name of the message you send.

target (Thing)

The thing to send a message to. It will receive a function call based on the name of the message (see below).

name (string)

The name of the message to send. This determines what function will be called on the target thing. If this is "Hello", for example, the function onHello() of the target thing will be called.

args (table) - optional

A table with additional parameters to pass. This will be received by the target thing as a parameter to the function call.

delay (number) - optional

This indicates how long to wait before delivering the message to the target Thing.

count = 0
-- Counter object is clicked
function onClick()
  count = count + 1
  -- Send the updated count to the sign
  send(getThing("Sign"),"CountUpdated",{count=count})
end

-- In the sign, you'd define onCountUpdated to receive this function onCountUpdated(args) setText(args.count) end

broadcast

broadcast(name, args, delay)

Broadcasts a message to all things in the room.

When you broadcast the message "Hello", for example, then the function onHello will be called on every Thing in the room that has that function defined in its script.

This works as a means of coordination between different Things. For example, you can have a button that, when clicked, starts playing some music and broadcasts a message "MusicStarted", and then every Thing in your room would get a call to their function onMusicStarted, if they have one. They could, for example, react by starting to dance.

name (string)

The name of the message to send. This determines what function will be called on other things. If this is "Hello", for example, the function onHello() of all other things will be called.

args (table) - optional

A table with additional parameters to pass. This will be received by the target things as a parameter to the function call.

delay (number) - optional

This indicates how long to wait before broadcasting the message.

on = false
function onClick()
  -- Toggle light switch
  on = not on
  playSound("lightswitch.mp3")
  -- Tell lights that the light switch was flipped,
  -- so they can turn off/on
  broadcast("LightSwitchFlipped",{on=on})
end

-- In the lights, you'd define onLightSwitchFlipped -- to react to that broadcast: function onLightSwitchFlipped(args) enableLight(args.on) end

๐Ÿ› ๏ธ Utilities

print

print(toPrint)

Displays a short message on the screen. The message will be visible during a few seconds. This is mostly for debugging.

toPrint (string)

The message to show.

function onClick()
  print("I was clicked")
end

openUrl

openUrl(url)

Opens a given url in a new tab in the browser, or in the default browser on mobile

url (string)

The url to open, must be fully qualified -- include 'http(s)://'

function onClick()
  openUrl("https://things.inc/")
end

randomPick

randomPick(array)

Returns a random element of the given array. Returns the element and its index. If the array is empty, returns (nil, nil).

array (array)

The array from which to pick an element.

GREETINGS = {"Hi", "Hello", "Good morning", "What's up?"}

function onClick() -- Say a random greeting when clicked. say(randomPick(GREETINGS)) end

unixTime

unixTime()

Returns the current time in seconds since epoch. This is also known as the "Unix time".

The Unix time represents how many seconds have elapsed since 00:00:00 UTC on January 1, 1970. I don't know what happened at that moment, but it must have been interesting.

This is especially useful to compute time differences: if you know the unix times of two events and you subtract the earlier from the later, you get the time elapsed in seconds.

This is a floating point value.

say("Unix time is " .. unixTime())

dateTime

dateTime(useUtc)

Gets the current date and time as a standard ISO string. For example, "2023-05-22 17:55:32".

useUtc (boolean) - optional

If true, then use UTC time, not the local time zone.

say("Right now is " .. dateTime())

roomTime

roomTime()

Gets the current "room time", that is the number of seconds elapsed since the code started. This is reset every time you re-enter Play mode.

say("The room time is " .. roomTime())

insert

insert(array, element)

Adds an element to the end of an array. If you want to insert the element at a specific index, use insertAt.

array (array)

The array to insert the element in. element (any)

The element to insert at the end of the array.

insertAt

insertAt(array, index, element)

Adds an element to the specified index of an array, displacing other elements. If you just want to add to the end, use insert.

array (array)

The array to insert the element in. index (number)

The index at which to insert the element. Original elements at this index and greater indices will be shifted to make room for the new element. element (any)

The element to insert.

remove

remove(array, index)

Removes an element from an array. Returns the removed element.

index (number)

The index of the element to remove. If not specified, removes from the end of the array.

openCamera

Thing:openCamera(options)

Opens a camera from the pespective of the current thing.

You cannot open a camera before the user interacts with the room.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

options (table) - optional

(Advanced) If present, this is a set of options that specify settings for the camera. See the "advanced" section in the takePhoto function for details on what options can be specified in this table. If this table is omitted, then the camera will open with whatever parameters the user had last set when using the camera.

function onClick()
  -- Opens the camera from the perspective of this thing.
  openCamera(options)
end

function onClick()
  -- Opens the camera from the perspective of the thing called "Camcorder".
  getThing("Camcorder"):openCamera()
end

๐Ÿ’ผ Session

setSessionValue

setSessionValue(key, value)

Sets a value on the current session. Session values persist from room to room if the transition happens through a goToRoom call where the @(keepSession) parameter is set to true, and both the current and the destination rooms belong to the same user. Session values are lost if the user reloads the page. Session values can be read with getSessionValue.

key (string)

The key of the value to set.

value (string, boolean, number) The value to set. This can be a string, a boolean or a number. But not a compound object like a table, array, etc. Use nil to clear a session value.

setSessionValue("gotKey", true)

clearSessionValue

clearSessionValue(key)

Clears a session value set with setSessionValue.

key (string)

The key of the value to clear.

clearSession

clearSession()

Clears all session values set with setSessionValue.

getSessionValue

getSessionValue(key)

Gets a value in the current session, previously set with setSessionValue in this or a previous room. This will return the value, or nil if the value is not found.

key (string)

The key of the value to get.

if getSessionValue("gotKey") then
  say("I see you brought the key.")
end

๐Ÿค– AI

aiCharacter

aiCharacter(primer, userText)

All-in-one AI conversation function. It's recommended that you call this from your onClick function.

This function makes the Thing behave like a basic AI character. For more advanced use cases, see aiChatCreate and aiChat, as those allow more fine-tuning.

Note that calling this function again while the previous result is still processing is a no-op, that is, the extra call will be ignored.

primer (string) - optional

This is the primer text that instructs the AI about who this character is and its personality. If omitted, a default prompt will be used based on the thing's name.

userText (string) - optional

This is what is being said to the AI, which it will respond to. If omitted, then the user will be prompted to enter something to say.

local PRIMER =
  "You are a sushi chef in a sushi restaurant. " ..
  "You are kind and cheerful and excited about offering " ..
  "different kinds of sushi to the customer."

function onClick() aiCharacter(PRIMER) end

aiChatCreate

aiChatCreate(introText)

Creates a new AI conversation. This won't actually cause the AI to answer; this only creates the conversation; to actually get the AI to answer, call aiChat.

This function returns a Chat ID which you must provide to aiChat.

introText (string)

An introduction text that explains to the AI who the character is and how it should behave.

aiChat

aiChat(chatId, userText, callback)

Continues an AI conversation by providing user input.

userText (string)

The text said by the user.

callback (function)

The function to call when the AI answers. This function will be passed the response.

โž• Math

distance

distance(x1, y1, z1, x2, y2, z2)

Calculates the distance between two points in 3D space. x1, y1, z1 (numbers)

The coordinates of the first point. x2, y2, z2 (numbers)

The coordinates of the second point.

min

min(a, b)

Returns the smallest of two numbers.

a, b (numbers)

The numbers to check.

-- Says 10, as 10 < 42.
say("The min is: " .. min(42, 10))
-- Says -5, as -5 < 2.
say("The min is: " .. min(2, -5))

max

max(a, b)

Returns the biggest of two numbers.

a, b (numbers)

The numbers to check.

-- Says 42, as 42 > 10.
say("The max is: " .. max(42, 10))
-- Says 2, as 2 > -5.
say("The max is: " .. max(2, -5))

abs

abs(x)

Returns the absolute value of a number.

x (number)

The number.

-- Says 42.
say("The abs is " .. abs(-42))
-- Says 42.
say("The abs is " .. abs(42))

floor

floor(x)

Returns the floor of a number, that is, the greatest integer not larger than the number.

For non-negative numbers, you can think of this as the "integer part of the number", so the floor of 42.912 is 42. The floor of 2.51 is 2, and so on.

Be careful with negative numbers: the floor of -1.7 is -2, the floor of -8.00001 is -9, and so on.

x (number)

The number.

-- Says 42.
say("The floor is " .. floor(42.813))
-- Says -43.
say("The floor is " .. floor(-42.813))

ceil

ceil(x)

Returns the ceiling of a number, that is, the smallest integer not smaller than the number.

x (number)

The number.

-- Says 42.
say("The ceil is " .. ceil(41.013))
-- Says -41.
say("The ceil is " .. ceil(-42.813))

round

round(x)

Rounds a number to the nearest integer.

x (number)

The number.

-- Says 42.
say("Rounded: " .. round(41.91))
-- Says 40
say("The ceil is " .. round(40.12))
-- Says -12
say("The ceil is " .. round(-12.12))
-- Says -82
say("The ceil is " .. round(-81.68))

sin

sin(degrees)

Returns the sine of an angle given in degrees.

degrees (number).

The angle, in degrees.

-- Says 0.5
say("The sine of 30 degrees is " .. sin(30))

cos

cos(degrees)

Returns the cosine of an angle given in degrees.

degrees (number).

The angle, in degrees.

-- Says 0.86602540378
say("The cosine of 30 degrees is " .. cos(30))

tan

tan(degrees)

Returns the tangent of an angle given in degrees.

degrees (number).

The angle, in degrees.

-- Says 1.0
say("The tangent of 45 degrees is " .. tan(45))

random

random(max)

Returns a random integer number between 1 and max.

max (number)

The maximum number.

-- Says a random number between 1 and 10, inclusive.
say("My favorite number is " .. random(10))

randomBetween

randomBetween(min, max)

Returns a random integer number in the given interval.

min (number).

The minimum number (inclusive). max (number).

The maximum number (inclusive).

-- Says a random number between 200 and 900, inclusive.
say("I have " .. random(200, 900) .. " alpacas")

randomFloat

randomFloat()

Returns a random floating-point number between 0 and 1, including 0 but excluding 1.

-- Says a random floating point number between 0 and 1.
say("I choose " .. randomFloat())
-- Says a random floating point number between 0 and 20.
say("I choose " .. (randomFloat() * 20))

randomSeed

randomSeed(seed)

Sets the random number seed. This is what determines what sequence of random numbers will come out of random number functions. Given the same seed, the sequence of random numbers you get will be the same.

-- Set the random seed to 17.
randomSeed(17)

๐Ÿงต Strings

toLowercase

toLowercase(s)

Converts a string into lowercase. s (string)

The string to convert.

toUppercase

toUppercase(s)

Converts a string into uppercase. s (string)

The string to convert.

substring

substring(s, startIndex, endIndex)

Returns a substring (piece) of a string. s (string)

The string to whose substring is to be returned. startIndex (number)

The index at which to start (inclusive). This is 1-based. endIndex (number)

The index at which to end (inclusive). This is 1-based. If omitted, the substring will end at the end of the string.

find

find(s, pattern)

Finds a pattern in a string. Returns the index where the pattern starts and where it ends. (remember indices are based on 1, so 1 is the first character of the string). If not found, then returns nil, nil.

s (string)

The string to search in. pattern (string)

The pattern to search for.

local s = "Lorem ipsum"
local i, j = findInString("Once upon a time", "upon")
-- Says "From 6 to 9"
say("From " .. i .. " to " .. j)

split

split(s, delimiter)

Splits a string using a given delimiter.

s (string)

The string to split. delimiter (string)

The delimiter to use. If this is the empty string, the string will be split character by character.

local s = "This is a test"
local pieces = split(s, " ")
-- pieces is now {"This", "is", "a", "test"}
-- So this says "test":
say(pieces[4])

join

join(strings, delimiter)

Joins an array of strings into a single string using the given delimiter.

strings (array)

The array of strings to join. delimiter (string)

The delimiter to use.

replaceAll

replaceAll(s, pattern, replacement)

Replaces all occurences of the given pattern in the given string, returning the new string (the original string is not changed).

s (string)

The string in which to search. pattern (string)

The pattern to search for. replacement (string)

What the pattern should be replaced with.

๐Ÿ“ท Photo

sharePhoto

sharePhoto(photo)

Shows the user a photo so they can share it. This is a photo that was previously taken with takePhoto.

Note that if you want to take and immediately share a photo, you can just use instantPhoto instead.

photo (photo)

The photo to share.

instantPhoto

Thing:instantPhoto(options)

Takes a photo from the current perspective of the Thing and opens up the photo UI so the user can save it. This takes into account the Thing's position and orientation (the local +Z axis).

If instead of showing the photo to the user, you want to use it in your room as media for an object, use takePhoto instead.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

options (table) - optional

(Advanced) If present, this is a set of options that specify settings for the picture. See the "advanced" section in the takePhoto function for details on what options can be specified in this table.

function onClick()
  instantPhoto()
end

-- (Advanced) Take a photo using specific camera parameters.
function onClick()
  instantPhoto({
    fieldOfView = 45,
    focalDepth = 92,
    focalDistance = 42.6
  })
end

takePhoto

Thing:takePhoto(options)

Takes a photo from the current perspective of the Thing and returns it as a Photo object. That can later be used to set the media of a thing. If instead you want to show it to the user right away so they can download or share it, use instantPhoto instead.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

options (table) - optional

(Advanced) If present, this is a set of camera settings for the picture. See the "Advanced" section below for more details on what can be in this table.

function onClick()
  -- Take a photo from my perspective.
  local photo = takePhoto()
  -- Show it on the TV.
  getThing("TV"):setMedia(photo)
end

-- (Advanced) Take a photo using specific camera parameters.
function onClick()
  local photo = takePhoto({
    fieldOfView = 45,
    focalDepth = 92,
    focalDistance = 42.6
  })
  -- Show it on the TV.
  getThing("TV"):setMedia(photo)
end

Advanced ▾
These are the possible parameters in the options table:
  • fieldOfView: the field-of-view angle (default 75).
  • focalLength: the focal length of the camera (default 1). Bigger = blurrier, smaller = sharper.
  • focalDistance: the distance from the camera at which objects will be the sharpest. How blurry everything else will be depends on the focalLength parameter.

๐Ÿ“” Comments

fetchComments

fetchComments(callback, continuationToken)

Fetches the comments for the current room. Comments are text or images that other users have posted. These can be displayed, for example, on a guestbook, on the wall, or anywhere else you can imagine.

callback (function)

The callback to call when the comments have been loaded.

continuationToken (string) - optional

If this is the first time you're calling, omit this parameter or pass nil. If you already got a page of results, then in the callback and you will get a token that you can pass here to retrieve more results.

-- Fetch comments
fetchComments(onCommentsFetched)

function onCommentsFetched(comments, continuationToken) -- Comments available in comments (an array) -- Each element has { text, author, timestamp } -- It may have a "photo" field too, if the comment has a photo. -- If the "photo" field is present, then the "aspect" field gives the photo's -- aspect ratio (width/height), in case that's useful to you.

-- If continuationToken is not nil, then there are more comments to fetch -- and you can fetch more with fetchComments(onCommentsFetched, continuationToken). end

promptForComment

promptForComment(callback)

Prompts the user for a (text) comment to send to the room. The user will have the choice to submit that comment or not. You don't need to do anything: comment submission is automatic.

callback (function) - optional

The callback to call when the user has submitted the comment. It will be passed the comment that the user submitted.

function onClick()
  promptForComment()
end

function onClick()
  promptForComment(onSentComment)
end

function onSentComment(comment) say("Thanks for your comment!") end

๐ŸŽฎ High Scores

loadHighScores

loadHighScores(callback)

Gets a list of high scores for the current room.

callback (function)

The callback to call when the high scores are loaded. This function is passed a boolean indicating success, an array of score entries, and the user's own score entry, if the user has a score in the current room. See the example below for details.

function onStart()
  -- Request the high scores. The callback will be called
  -- when the scores are loaded.
  loadHighScores(processHighScores)
end

function processHighScores(success, scores, mine) if not success then print("error loading scores") return end -- scores: an array of high scores ordered from -- best to worst (it contains up to 20 scores). for i = 1, #scores local t = scores[i] -- Each element has: -- uname, score, daysAgo, photo, -- timestamp, timestampLocal print(t.uname .. " got " .. t.score .. " " .. t.daysAgo .. " day(s) ago") end -- If the user has a score in this room, then it's -- reported in the "mine" parameter. Otherwise, "mine" is nil. if mine then print("User got " .. mine.score .. " " .. mine.daysAgo .. " day(s) ago") end end

submitHighScore

submitHighScore(score, callback)

Submits a high score for the current user for the current room.

score (number)

The score to submit. NOTE: if the user already has a score in this room, then the greater of the scores will be kept. So if the user already had a score of 1000 and you submit 790, the submission will have no effect (the 1000 will be kept), but if you submit 1200, then the user's new score will be 1200.

callback (function) - optional

If provided, then this callback will be called when the score submission has gone through. This callback has a single parameter: a boolean indicating if the operation was successful or not.

function onClick()
  -- Submit a score of 123 for the current user
  submitHighScore(123)
end

function onClick()
  -- Submit a score of 123 for the current user
  -- and check if it was successful.
  submitHighScore(123, handleScoreSubmitted)
end

function handleScoreSubmitted(success) if success then say("Score submitted!") else say("Failed to submit. Are you signed in and connected to the internet?") end end

deleteHighScore

deleteHighScore(callback)

Deletes the high score for the current user for the current room.

callback (function) - optional

If provided, then this callback will be called when the score deletion has gone through. This callback has a single parameter: a boolean indicating if the operation was successful or not.

function onClick()
  -- Delete the high score for the current user in the current room.
  deleteHighScore()
end

function onClick()
  -- Delete the high score for the current user in the current room.
  -- and check if it was successful.
  submitHighScore(123, handleScoreDeleted)
end

function handleScoreDeleted(success) if success then say("Score deleted!") else say("Failed to delete. Are you signed in and connected to the internet?") end end

๐Ÿฆ„ Thing

getThing

getThing(thingName)

Gets a thing by name.

thingName (string)

The name of the thing. If there is more than one thing with the same name, this will return an arbitrary one. To avoid this kind of confusion, we recommend that you give a unique name to each Thing in the room (or at least the ones you intend to reference via script).

local ball = getThing("ball")

getAllThings

getAllThings()

Gets a list of all the Things in the room. This does NOT include things that are children of other things.

say

Thing:say(msg)

Shows a speech bubble.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

msg (string)

The message to say in the speech bubble. This can either be a single string, or an array. If it's an array, the messages in the array will be said one at a time in sequence. This can also be nil to dismiss the current speech bubble.

-- Say hello when clicked.
function onClick()
  say("Hello, how are you?")
end

-- If you want to say several things in sequence, pass an array
-- instead of a single string. Don't forget the curly braces to
-- indicate that it's a Lua array.
say({
  "Hi, I'm Bruno",
  "I'm an engineer",
  "I like programming."
})

getPosition

Thing:getPosition()

Gets the thing's position.

Note: a Thing's pivot is the center-bottom of its bounding box, so if it's at (0, 0, 0), it means the center point of its bottom side is at (0, 0, 0). If you want the geometric center of the Thing instead, use getCenter.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

This returns the three coordinates (x, y and z) of the thing's position.

local x, y, z = getPosition()

getLocalPosition

Thing:getLocalPosition()

(Advanced) Gets the thing's LOCAL position.

This is the position of the Thing relative to its parent. If you want the Thing's position in the room, use getPosition instead.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

This returns the three coordinates (x, y and z) of the thing's local position.

local lx, ly, lz = getLocalPosition()

getRotation

Thing:getRotation()

Gets the thing's rotation.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

This returns the three rotation angles (rx, ry and rz) of the thing's rotation (in world space).

local rx, ry, rz = getRotation()

getLocalRotation

Thing:getLocalRotation()

(Advanced) Gets the thing's LOCAL rotation.

This is the rotation of the Thing relative to its parent. If you want the Thing's rotation in the room, use getRotation instead.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

This returns the three rotation angles (rx, ry and rz) of the thing's local rotation (relative to its parent).

local rx, ry, rz = getLocalRotation()

setPosition

Thing:setPosition(x, y, z)

Sets the thing's position instantaneously. If you want to animate it instead of moving it instantaneously, see startMoveTo.

Note: a Thing's pivot is the center-bottom of its bounding box, so if it's at (0, 0, 0), it means the center point of its bottom side is at (0, 0, 0).

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

x, y, z (number)

The coordinates.

-- Go to the center of the room
setPosition(0, 0, 0)

setLocalPosition

Thing:setLocalPosition(lx, ly, lz)

(Advanced) Sets the thing's LOCAL position instantaneously. The local position is the position of the Thing relative to its hierarchical parent. If the Thing has no parent, then the local position is exactly the same as its regular position (also called world position).

If you just want to set its regular position in world coordinates, use setPosition instead.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

lx, ly, lz (number)

The local coordinates (relative to the parent).

-- Position myself such that I'm 10 units in front of my parent (that is, 10 units away
-- from my parent in the direction that my parent is facing).
setLocalPosition(0, 0, 10)

setRotation

Thing:setRotation(rx, ry, rz)

Sets the thing's rotation instantaneously.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

rx, ry, rz (number)

The rotation angles, that is, the rotation angle around each of the axes X, Y and Z. Quick reminder: the X rotation angle controls the pitch (changing the pitch will tilt the object up and down), the Y rotation angle controls the yaw (changing yaw will rotate the object on the plane), and the Z rotation controls the roll (remember "do a barrel roll?").

-- Sets this Thing's rotation so it's 90 degrees rotated on the Y axies.
-- So if it was originally facing forward, now it's facing right.
setRotation(0, 90, 0)

setLocalRotation

Thing:setLocalRotation(rx, ry, rz)

(Advanced) Sets the thing's local rotation instantaneously. This sets the rotation of the Thing relative to its parent.

If you just want to set its world rotation independently of the parent, use setRotation instead.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

rx, ry, rz (number)

The rotation angles, that is, the rotation angle around each of the axes X, Y and Z. Quick reminder: the X rotation angle controls the pitch (changing the pitch will tilt the object up and down), the Y rotation angle controls the yaw (changing yaw will rotate the object on the plane), and the Z rotation controls the roll (remember "do a barrel roll?").

-- Sets this Thing's local rotation so it's 90 degrees rotated on the Y axis,
-- relative to the direction its parent is facing. For example, if the parent is looking
-- towards the west, then we would look towards the north (90 degrees clockwise).
setLocalRotation(0, 90, 0)

getCenter

Thing:getCenter()

Gets the position of this thing's center (x, y, z).

This is different from getPosition because this one gives the center of the object, as opposed to its pivot (center-bottom).

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

local cx, cy, cz = getCenter()

getName

Thing:getName()

Gets a thing's name.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

say("Hi, I'm " .. getName())

setTint

Thing:setTint(colorHex)

Sets this Thing's tint color.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

colorHex (string)

The color to set the thing to, in hexadecimal. For example, "#ff0000" would be red.

-- Sets the Thing's tint color to red.
setTint("#ff0000")

getTint

Thing:getTint()

Gets the Thing's tint color as a hex string.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

say("My color is " .. getTint())

startMoveTo

Thing:startMoveTo(x, y, z, duration)

Moves smoothly to a given position (animating). This will animate the movement, in contrast with setPosition which is instantaneous.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

x, y, z (number)

The position to move it.

duration The duration of the movement, in seconds. Default: 1.

-- Smoothly moves to position (10, 0, 10) in 3 seconds.
startMoveTo(10, 0, 10, 3)

stopMove

Thing:stopMove()

Stops a "move" animation on the Thing. This stops the animation previously added with startMoveTo or startMoveBy.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

stopMove()

setVelocity

Thing:setVelocity(vx, vy, vz)

Sets a Thing's velocity directly. Note that this is INCOMPATIBLE with startMoveBy and startMoveTo.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

vx, vy, vz (number)

The velocity to set, in units per second. You can pass nil for any of the arguments to not set that component (that is, to keep the current value of that component).

function onClick()
  setVelocity(10, 0, 0)
end

setSpin

Thing:setSpin(vx, vy, vz)

Sets a Thing's angular velocity directly. Note that this is INCOMPATIBLE with startMoveBy and startMoveTo. Angular velocity means how fast it's spinning about each of its axes, in degrees per second.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

vx, vy, vz (number)

The angular velocity to set, in degrees per second. You can pass nil for any of the arguments to not set that component (that is, to keep the current value of that component).

function onClick()
  -- Spin at 45 degrees/second about the Y axis.
  setSpin(0, 45, 0)
end

getVelocity

Thing:getVelocity()

Gets the Thing's current velocity. This only works for Things that have a physics type for which velocity makes sense (everything except Trigger or Passthrough).

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

function onClick()
  local x, y, z = getVelocity()
  say("my velocity is " .. x .. "," .. y .. "," .. z)
end

getSpin

Thing:getSpin()

Gets the Thing's current angular velocity (spin speed). This only works for Things that have a physics type for which velocity makes sense (everything except Trigger or Passthrough).

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

function onClick()
  local x, y, z = getSpin()
  say("my angular velocity is " .. x .. "," .. y .. "," .. z)
end

startSpin

Thing:startSpin(speed, duration, axis)

Starts spinning.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

speed (number) - optional

The angular speed of the spin, in degrees per second. Positive means clockwise, negative is counter-clockwise. If omitted, will default to 90 degrees per second.

duration (number) - optional

How long to spin for. If omitted, this will default to infinity (spin forever)

axis (string) - optional

By default the spin will be around the Y axis (this is normally what you want), but if you want to spin on the X or Z axis, pass "X" or "Z" in this parameter.

-- When the user clicks, start or spinning.
isSpinning = false
function onClick()
  if isSpinning then
    stopSpin()
  else
    -- 360 deg/sec = 1 full turn every second
    startSpin(360)
  end
  isSpinning = not isSpinning
end

stopSpin

Thing:stopSpin()

Stops a "spin" animation on the Thing. This stops the animation previously added with startSpin.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

-- When the user clicks, start or spinning.
isSpinning = false
function onClick()
  if isSpinning then
    stopSpin()
  else
    -- 360 deg/sec = 1 full turn every second
    startSpin(360)
  end
  isSpinning = not isSpinning

startMoveBy

Thing:startMoveBy(dx, dy, dz, duration)

Moves smoothly by a given delta (animating). This will animate the movement, in contrast with setPosition which is instantaneous. This function performs relative movement (it takes the amount of movement as parameters, not the final position). If you want absolute movement, see startMoveTo.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

dx, dy, dz (number)

The delta (amount by which to move).

duration The duration of the movement, in seconds. Default: 1.

-- Smoothly 20 units east in 3 seconds.
startMoveBy(20, 0, 0, 3)

startBounce

Thing:startBounce(amplitude, period, duration, uneven)

Starts a "bounce" animation on the Thing. This animation will make it grow a bit and shrink periodically, giving the impression that it's wobbling, or emitting sound, etc. Great for sound-emitting devices like speakers, etc.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

amplitude (number) - optional

The range of movement (defaults to 0.05).

period (number) - optional

The period of the movement, in seconds. The larger this number, the slower the movement will be. This defaults to 0.5, so it's a full cycle every 0.5 seconds.

duration (number) - optional

How long the effect should be active for, in seconds. By default, this is infinity, so the effect will remain active forever. If you don't want it to last forever, use this parameter to say how long it should last.

uneven (bool) - optional

If this is true, then the motion is uneven across the axes, meaning it will add a bit of chaos to it.

-- Start the bounce animation with default parameters.
startBounce()
-- Start the bounce animation with amplitude 0.1, period 1, for 5 seconds,
-- with uneven movement.
startBounce(0.1, 1, 5, true)

stopBounce

Thing:stopBounce()

Stops a "bounce" animation on the Thing. This stops the animation previously added with startBounce.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

stopBounce()

startSway

Thing:startSway(amplitude, frequency, axis)

Starts a sway motion (tilting to one side and then the other repeatedly).

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

amplitude (number) - optional

The amplitude of the motion, in degrees to each side. If omitted, defaults to 30.

frequency (number) - optional

How many times a second it completes a full sway motion, returning to the original position. If omitted, defaults to 0.5.

axis (string) - optional

By default the sway will be around the X axis. If you prefer the Z axis, pass Z instead.

-- When the user clicks, start swaying back and forth.
function onClick()
  startSway()
end

-- When the user clicks, start swaying back and forth with amplitude 60
-- frequency 0.2 and on the Z axis.
function onClick()
  startSway(60, 0.2, "z")
end

stopSway

Thing:stopSway()

Stops a sway motion previously started with startSway.

startSwivel

Thing:startSwivel(amplitude, frequency)

Starts a swivel motion (turning from side to side repeatedly).

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

amplitude (number) - optional

The amplitude of the motion, in degrees to each side. If omitted, defaults to 30.

frequency (number) - optional

How many times a second it completes a full swivel motion, returning to the original position. If omitted, defaults to 0.5.

-- When the user clicks, start swiveling back and forth.
function onClick()
  startSwivel()
end

-- When the user clicks, start swiveling back and forth 
-- with amplitude 60 and a frequency of 0.2
function onClick()
  startSwivel(60, 0.2)
end

stopSwivel

Thing:stopSwivel()

Stops a swivel motion previously started with startSwivel.

startBackAndForth

Thing:startBackAndForth(dx, dy, dz, frequency)

Starts a back and forth motion.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

dx, dy, dz (number) - optional

The amplitude of the movement in the x, y and z directions. By default, this is 0, 0, 10

frequency (number) - optional

How many times a second it completes a full motion, returning to the original position. If omitted, defaults to 0.5.

-- When the user clicks, start moving back and forth.
function onClick()
  startBackAndForth()
end

-- When the user clicks, start moving back and forth in the (5,0,10) direction,
-- with frequency 0.4.
function onClick()
  startBackAndForth(5, 0, 10, 0.4)
end

stopBackAndForth

Thing:stopBackAndForth()

Stops a back and forth motion previously started with startBackAndForth.

startUpAndDown

Thing:startUpAndDown(amplitude, frequency)

Starts an up and down motion.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

height (number) - optional

The height of the movement. By default 10.

frequency (number) - optional

How many times a second it completes a full motion, returning to the original position. If omitted, defaults to 0.5.

-- When the user clicks, start an up and down motion.
function onClick()
  startUpAndDown()
end

-- When the user clicks, start moving up and down with an amplitude of 5 and
-- with frequency 0.4.
function onClick()
  startUpAndDown(5, 0.4)
end

stopUpAndDown

Thing:stopUpAndDown()

Stops an up-and-down motion previously started with startUpAndDown.

applyForce

Thing:applyForce(forceX, forceY, forceZ)

Applies a physical force on this Thing in the given force direction. Note that this will only have an effect on Things that have physics enabled.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

forceX, forceY, forceZ (number)

The force vector to apply.

-- Apply an upwards force on this Thing when it's clicked
function onClick()
  applyForce(0, 50, 0)
end

setText

Thing:setText(text)

Sets the text of the Thing. This only works for Things that can have text on them, like signs, etc.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

text (string)

The text to set.

function onClick()
  setText("Hello, world!")
end

setMedia

Thing:setMedia(mediaName)

Sets a new media on the Thing. This only works for Things that can have media, like TVs, etc. If you want to set it to show a video channel instead of an image, use setMediaChannel.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

mediaName (string)

The media to use. This must be the name of a file in the room's media library. For now only images are supported.

function onClick()
  setMedia("cat.png")
end

getMedia

Thing:getMedia()

Gets the media of a Thing. This only works for Things that can have media, like TVs, etc.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

function onClick()
  say("My media is .. " .. getMedia())
end

enableLight

Thing:enableLight(enable)

Enable/disable a Thing's light. This only works for Things that are light sources like lamps, etc.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

enable (boolean) - optional

If true, enable the light. If false, disable the light. If this is ommitted, it defaults to true.

-- Toggle light on and off when the user clicks.
isOn = false
function onClick()
  isOn = not isOn
  enableLight(isOn)
end

disableLight

Thing:disableLight()

Disable a Thing's light.

Synonym for enableLight with an argument of false.

getCloudString

Thing:getCloudString(varName, defaultIfNotFound)

Gets a string value from the Thing's cloud memory.

Cloud memory is like a set of variables that retain their value from visit to visit to a given room. If you set a value in cloud memory, it will be available to all users on future visits of the room. You can use this to implement persistent score boards, visitor counters, click counters, etc. IMPORTANT: Cloud memory is private to each Thing. A Thing can't read or write the cloud variables of another Thing.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

varName (string)

The name of the variable to read from.

defaultIfNotFound (string) - optional

The value to use if the given variable doesn't exist yet. If omitted, this defaults to the empty string "".

-- When the room starts, set my text to the value of the cloud variable
-- 'lastQuote'. If no quote has been set, use one from Albert Einstein.
function onStart()
  setText(getCloudString("lastQuote", "Hi, I'm Albert. - Albert Einstein"))
end

setCloudString

Thing:setCloudString(varName, varValue)

Sets a string value on the Thing's cloud memory. It can later be read with getCloudString on the current or future visits to this room.

Cloud memory is like a set of variables that retain their value from visit to visit to a given room. If you set a value in cloud memory, it will be available to all users on future visits of the room. You can use this to implement persistent score boards, visitor counters, click counters, etc. IMPORTANT: Cloud memory is private to each Thing. A Thing can't read or write the cloud variables of another Thing.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

varName (string)

The name of the variable to read from.

varValue (string)

The value to set the variable to.

-- When the user clicks this button, set the "lastQuote" to
-- a famous one by Donald Knuth.
function onStart()
  setCloudString("lastQuote",
    "Premature optimization is the root of all evil. - Donald Knuth")
end

getCloudInt

Thing:getCloudInt(varName, defaultIfNotFound)

Gets an integer value from the Thing's cloud memory.

Cloud memory is like a set of variables that retain their value from visit to visit to a given room. If you set a value in cloud memory, it will be available to all users on future visits of the room. You can use this to implement persistent score boards, visitor counters, click counters, etc. IMPORTANT: Cloud memory is private to each Thing. A Thing can't read or write the cloud variables of another Thing.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

varName (string)

The name of the variable to read from.

defaultIfNotFound (number) - optional

The value to use if the given variable doesn't exist yet. If omitted, this defaults to 0.

-- When the room starts, set my text to the value of the cloud variable
-- 'score'. If no score has been set, use 0.
function onStart()
  setText(getCloudInt("score"))
end

setCloudInt

Thing:setCloudInt(varName, varValue)

Sets an integer value on the Thing's cloud memory. It can later be read with getCloudInt on the current or future visits to this room.

NOTE: If you want to add to a cloud integer variable, use addToCloudInt instead, as it will correctly handle conflicts where two people try to add to the same variable at once.

Cloud memory is like a set of variables that retain their value from visit to visit to a given room. If you set a value in cloud memory, it will be available to all users on future visits of the room. You can use this to implement persistent score boards, visitor counters, click counters, etc. IMPORTANT: Cloud memory is private to each Thing. A Thing can't read or write the cloud variables of another Thing.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

varName (string)

The name of the variable to read from.

varValue (number)

The integer value to set the variable to.

-- When the user clicks this button, reset the score to 0.
function onClick()
  setCloudInt("score", 0)
end

addToCloudInt

Thing:addToCloudInt(varName, delta)

Adds a number to a value on the Thing's cloud memory. It can later be read with getCloudInt on the current or future visits to this room.

NOTE: This function automatically handles conflicts where multiple users are trying to add to the same variable. So if one user adds 20 and another user in another session adds 30, the variable will correctly increase by 50.

Cloud memory is like a set of variables that retain their value from visit to visit to a given room. If you set a value in cloud memory, it will be available to all users on future visits of the room. You can use this to implement persistent score boards, visitor counters, click counters, etc. IMPORTANT: Cloud memory is private to each Thing. A Thing can't read or write the cloud variables of another Thing.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

varName (string)

The name of the variable to read from.

delta (number)

The value to add to the variable. This can be positive, negative or zero.

-- When the user clicks this button, increase the score. This score is
-- shared by all users who visit the room.
function onClick()
  addToCloudInt("score", 1)
end

setPhysicsType

Thing:setPhysicsType(physicsType)

Sets the Thing's physics behavior.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

physicsType (string)

Physics type. This can be "kinematic", "upright", "tumbly", or "passthrough".

-- When this thing gets clicked, make the object tumbly (so it will start to fall,
-- etc).
function onClick()
  setPhysicsType("tumbly")
end

isKinematic

Thing:isKinematic()

Returns true if this thing is KINEMATIC, false if DYNAMIC.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

isDynamic

Thing:isDynamic()

Returns true if this thing is DYNAMIC, false if KINEMATIC.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

getPhysicsType

Thing:getPhysicsType()

Returns the Thing's physics type.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

function onClick()
  say("My physics type is " .. getPhysicsType())
end

getForwardDir

Thing:getForwardDir()

Returns the thing's forward direction. This is the direction of the Thing's local Z axis, that is, where it thinks "forward" is. This is different from the world's Z axis. For example, if you're standing in the room, your forward direction is the direction in which your nose is pointed.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

function onClick()
  -- Get my forward direction.
  local fx, fy, fz = getForwardDir()
  -- Move 20 units along my forward direction.
  startMoveBy(fx * 20, fy * 20, fz * 20, 1)
end

getRightDir

Thing:getRightDir()

Returns the thing's 'right' direction. This is the direction of the Thing's local X axis, that is, where it things "right" is. This is different from the world's X axis. For example, if you're standing in the room, your right direction is the direction in which your right hand points when you extend it.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

function onClick()
  -- Get my right direction.
  local fx, fy, fz = getRightDir()
  -- Move 20 units along my right direction.
  startMoveBy(fx * 20, fy * 20, fz * 20, 1)
end

getUpDir

Thing:getUpDir()

Returns the thing's 'up' direction. This is the direction of the Thing's local Y axis, that is, where it things "up" is. This is different from the world's Y axis. For example, if you're standing in the room, and raise your arm high above your head, the up direction is where you're pointing. So if you're standing up, that direction would be towards the ceiling. But if you were lying down, then your "up" direction would be pointing towards your bedroom wall. And if you were a bat hanging upside down from the ceiling (Things, Inc. does not recommend that you hang upside down from the ceiling) then your "up" direction would be towards the floor, what non-bat people would call "down".

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

function onClick()
  -- Get my up direction.
  local fx, fy, fz = getUpDir()
  -- Move 20 units along my up direction.
  startMoveBy(fx * 20, fy * 20, fz * 20, 1)
end

getBackDir

Thing:getBackDir()

The opposite of getForwardDir.

getLeftDir

Thing:getLeftDir()

The opposite of getRightDir.

getDownDir

Thing:getDownDir()

The opposite of getUpDir.

setFrame

Thing:setFrame(frameNo)

Sets this thing's animation frame number. This will cause the Thing to stop playing its animation (it will remain in the given frame number until it's set to something else).

frameNo (number)

The frame to show. This is counted from 1 to N where N is the number of animation frames.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

function onClick()
  -- Sets animation frame to frame# 2 (the second frame).
  setFrame(2)
end

setAnimation

Thing:setAnimation(animMode, fps, startFrame, endFrame)

Sets this thing's animation parameters. This overrides setFrame.

animMode (string)

The animation mode. This can be: "off", "loop", "pingpong", "shuffle" or "single". "off" means the animation will stay at the given start frame and never change. "loop" means it will loop forever, going back to the first frame when it goes past the end. "pingpong" means it will go forward then backwards then forwards, etc. "shuffle" will show the animation frames in random order and "single" will play the animation just once and stop at the last frame.

fps (number) - optional

The animation speed in frames per second.

startFrame (number) - optional

The frame number at which the animation should start (1 is the first frame).

endFrame (number) - optional

The frame number at which the animation should end (remember 1 is the first frame). You can use -1 to mean the last frame.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

function onClick()
  -- Loop frames 2, 3, 4 at a speed of 2.5 fps.
  setAnimation("loop", 2.5, 2, 4)
end

getParent

Thing:getParent()

Gets the Thing's parent.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

local myParent = getParent()
if myParent then
  say("My parent is " .. myParent:getName())
else
  say("I have no parent.")
end

getChild

Thing:getChild(childName, recursive)

Gets a child by name.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

childName (string)

The name of the child to search for.

recursive (boolean) - optional

If false (default), only search direct children. If true, then this will also search for grandchildren, great-grandchildren, etc (all descendants).

-- Get an object that's called Propeller and is my direct child
-- (this would ignore other objects called Propeller that
-- are not my children).
local myPropeller = getChild("Propeller")
myPropeller:startSpin()

getChildren

Thing:getChildren()

Gets a list of all the Things that are children of the current thing. This is NOT recursive, that is, it won't return children of children (if you want that, use getDescendants).

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

local myChildren = getChildren()
-- Have all my children say hello.
for i = 1, #myChildren do
  myChildren[i]:say("Hello.")
end

getDescendants

Thing:getDescendants()

Gets a list of all the Things that are descendants of the current thing, that is, recursively enumerates children, children of children, children of children of children, and so and so forth. If you just want the direct children without recursion, use getChildren instead.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

local myDescendants = getDescendants()
-- Have all my descendants say hello.
for i = 1, #myDescendants do
  myDescendants[i]:say("Hello.");
end

prompt

Thing:prompt(prompt, callback)

Asks the user to input some text.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

prompt (string)

The prompt text to show to the user. callback (function)

The function to call when the user answers.

function onClick()
  prompt("What's your name?", nameEntered)
end

function nameEntered(name) say("Oh, hello " .. name .. ". How are you?") end

requestClone

Thing:requestClone(options)

(Advanced!) Requests that the thing be cloned, that is, creates a new thing that's identical to the current thing.

This method does NOT return the new Thing (contrary to what one might expect), because thing cloning needs to be asynchronous for performance reasons. For the same reason, calling getThing() with the name of the clone won't work immediately - you must wait until at least the next frame, or provide a callback in options.callback.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

options (table) - optional

If present, this argument is a table with additional options specifying how to make the clone.

Advanced ▾

These are the possible parameters in the options table:
  • x, y, z: the world position of the clone.
  • offsetX, offsetY, offsetZ: the relative position of the clone, relative to the template's position. For example if offsetZ is 10 it means 10 units in front of the template. This is incompatible with x, y, z.
  • rx, ry, rz: the rotation of the clone. If not specified this will be the same rotation as the template.
  • callback: a function to call when the clone has been created. This function will be passed a reference to the clone.
  • msgName: if present, the name of a message to send to the clone when it's created.
  • msgArgs: if present, this is a Lua table containing the arguments of the message to send to the clone when it's created.
  • name: the name to set on the clone.

requestDelete

Thing:requestDelete()

Requests that a Thing be deleted. It will only be deleted at runtime (while in Play/Preview mode), not in the actual room, of course.

Deletion is asynchronous, so the deleted thing may still exist during the current frame but will disappear at the end of the frame.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

getOpacity

Thing:getOpacity()

Gets the Thing's current opacity value.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

function onClick()
  local opacity = getOpacity()
  say("my opacity is " .. opacity)
end

setOpacity

Thing:setOpacity(opacity)

Sets the Thing's current opacity value.

opacity (number)

The opacity to set, where 0 is fully transparent and 1 is fully opaque.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

-- Make this thing semi-transparent when clicked.
function onClick()
  setOpacity(0.5)
  say("I'm now semi-transparent.")
end

setScale

Thing:setScale(scale)

Sets the Thing's current scale.

scale (number)

The scale to set, where 1 is the normal scale, 2 would be twice as big, etc.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

-- Make this thing half the size when clicked.
function onClick()
  setScale(0.5)
  say("I'm tiny now.")
end

getScale

Thing:getScale()

Gets the Thing's current scale.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

function onClick()
  local scale = getScale()
  say("My scale is " .. scale)
end

๐ŸŽž๏ธ Video

startStream

Thing:startStream(channelNumber)

Starts streaming video taken from the perspective of this Thing, and puts it in the given channel number (1 - 4). Things with screens can tune in to receive that video by using setMediaStream and passing the same channel.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

channelNumber (integer)

The channel number to stream to. This can be 1, 2, 3 or 4.

function onClick()
  -- Start streaming to channel 1.
  startStream(1)
end

stopStream

Thing:stopStream()

Stops streaming video that was previously started with startStream.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

function onClick()
  -- Stop streaming.
  stopStream()
end

setMediaStream

Thing:setMediaStream(channelNumber)

Sets this Thing's media to show a video channel (similar to how setMedia can be used to show a static image).

For this to show anything, some Thing needs to be streaming to that channel, naturally, via a call to startStream.

This is a Thing method. It can be called on its own to operate on the current Thing, or can be called on another Thing. See Thing methods for more information.

channelNumber (integer)

The channel to show. This can be 1, 2, 3 or 4.

function onClick()
  -- Make the camera start streaming to channel 1.
  getThing("Camera"):startStream(1)
  -- Have the TV show channel 1.
  getThing("TV"):setMediaStream(1)
end