Make a game
Lua scripting Beta
Everything the VR Realms nodes can do, you can also type. Drop a VR Realms Script actor into your level, write Lua in it, and it runs when the world starts. Blueprints keep working exactly as before: Lua is a second way, for people who would rather write code than wire nodes.
Your first scriptThe script windowHost or every machineText on a widgetLua in two minutesFrom Blueprints to LuaTestingBuild a gameWhen something goes wrongEvery node in LuaEventsTimers, objects, zonesExamplesWhat a script cannot do
Your first script
- In the Place Actors panel, search VR Realms Script and drag it anywhere into your level.
- In its Details, click Open Script Editor and type:
vrr.on_player_join(function(player)
player:say("Hi " .. player.name .. ", welcome to my world!")
end)
- Save with Ctrl+S and play your world. A mistake shows as Script error: ... on the host's screen while Show Errors To Host is ticked.
Things in your level are found by their actor tag: select a mesh, then in Details under Actor, Tags, add BigGate. In the script, world.find("BigGate") gives it to you.
You can mix Lua and Blueprints. A script can run your Blueprints' custom events (obj:tell_everyone("MyEvent")) and fire the same channels as VRSend / VRWhen tags. Use several Script actors for several jobs: each one runs on its own.
The script window
Open Script Editor opens a big window of its own, which you can resize, maximize or move to a second screen.
- Colours: keywords, text, numbers, comments, the
vrrandworldcommands and function calls each have their own colour. - An error check while you type. The bottom line says No syntax errors or, for example, Line 5: '=' expected near 'x'. Go to the error jumps to that line.
- Commands and starter scripts on the right: every command on this page and every example, with a search box. Hover one to see what it does, click it to add ready-to-run code where your cursor is.
- Save (Ctrl+S) puts the text into the actor as one undo step. Playing saves for you, and closing with unsaved text asks first.
- Suggestions while you type. After
vrr.,world.,player.orx:a list shows the commands that fit; three letters of a name (annou) are enough, and picking one writes the whole call. Inside the brackets a hint shows how to call it. Up and Down to choose, Tab or Enter to take, Esc to close. - Line numbers, Ctrl+F to find (Enter or F3 for the next one, Shift for the one before) and Ctrl+G to go to a line.
- Tab and Shift+Tab move every selected line four spaces in or out. The bottom right shows the line and column and how much of the 65,536 characters you have used.
- Open in your own editor: VS Code, Notepad++, Visual Studio, the Windows default or a program you choose. A save there comes straight back into the window and the actor. In VS Code, the free Lua extension then suggests every VR Realms command too.
Host or every machine
The Run On setting is the Lua version of the (Local) and (Server) labels on the nodes.
| Run On | Meaning | Use it for |
|---|---|---|
| Host only (default) | One copy, on the host. Its (Server) commands change the world for everyone. | Game rules: points, teams, rounds, gates, races, chat commands. |
| Every player's machine | A copy on each machine. vrr.me() is the person at that machine. | What one person sees or does: a lantern in your hand, fades, input, saved text, vibration. |
vrr.me() is a different person on every machine, so never use it to decide who the monster chases. (Server) commands only do something in the host's copy: vrr.is_host_copy() tells you which one you are in.Showing text on a widget
A script does not make widgets itself. Your Blueprint holds the widget, and the script tells it what to show.
- Make a Widget Blueprint with a Text block. Tick Is Variable on the Text block and name it, for example
Message. - Make an actor Blueprint and add a Widget Component. Set its Widget Class to your widget and its Space to World (that is the one that reads well in a headset). Give the actor a tag, for example
VisitsPanel, and place it in your level. - In that actor's Event Graph, add a custom event
ShowTextwith two inputs:Text(String) andNumber(Float). From it: Widget (the component) → Get User Widget Object → Cast To your widget →Message→ Set Text, with the string through To Text. - In the script, find it by its tag and pick how far the call goes:
| Lua | Where the event runs | Use it for |
|---|---|---|
panel:call("ShowText", text, number) | This machine only. Nothing goes over the network. | What one person should see, from an Every player's machine script: their visits, their best time. |
panel:tell_everyone("ShowText", text, number) | Every machine, through the host. | What everyone sees, from a Host only script: a round timer, a scoreboard. |
panel:tell_host("ShowText", text, number) | The host only. | Game rules that live in a Blueprint. |
local panel = world.find("VisitsPanel")
panel:call("ShowText", "Hello, " .. vrr.me().name .. "!", 0)
The event may have any of the inputs Sender, Text and Number; they are matched by name, and the rest are left out. Only custom events of your own Blueprints can be run this way, never engine functions. The whole visits example is under Examples.
Lua in two minutes
local score = 0 -- a variable (local = only in this script)
score = score + 1
local name = "Ana"
local text = "Hello " .. name -- .. joins text
if score > 10 then -- if / elseif / else / end
vrr.announce(text)
end
for i = 1, 3 do vrr.log(i) end -- counts 1, 2, 3
local list = { "red", "blue" } -- a list starts at 1
for i, team in ipairs(list) do vrr.log(i, team) end
local function double(x) return x * 2 end
player:say("hi") -- a colon calls a player's or object's command
vrr.after(5, function() vrr.announce("5 seconds later") end) -- functions can be passed around
Plain Lua is all there: math (math.random, math.floor), string (text:sub, string.format), table (table.insert), utf8 and pcall.
From Blueprints to Lua
If you know Blueprints, you already know how a script thinks. The same ideas, side by side:
| Blueprint | Lua |
|---|---|
| Event BeginPlay | The top of the script: it runs once when the world starts. |
| A variable (Integer, Float, String, Boolean) | local score = 0, local name = "Ana", local open = false |
| Set a variable | score = score + 1 |
| Custom event or function | local function give(player, n) player:add_points(n) end |
| Branch | if score > 10 then ... else ... end |
| ==, !=, AND, OR, NOT | ==, ~=, and, or, not |
| For Loop | for i = 1, 10 do ... end |
| For Each Loop | for i, item in ipairs(list) do ... end |
| While Loop | while ... do ... end (keep loops short: one that never ends is stopped) |
| Array: Make, Add, Length, Get | local list = { "red", "blue" }, table.insert(list, "green"), #list, list[1] (lists start at 1) |
| Map | local best = {}, then best[player.id] = 12.5 |
| Is Valid | if obj then ... end |
| Delay | vrr.after(2, function() ... end) |
| Set Timer by Event (looping), Clear Timer | local id = vrr.every(1, function() ... end), vrr.cancel(id) |
| Print String | vrr.log("text") or print("text") |
| Append, Format Text | "Hi " .. name, string.format("%.2f s", seconds) |
| Random Integer in Range | math.random(1, 6) |
| Get All Actors With Tag | world.find_all("Coin") (world.find("Coin") for the first one) |
| Set Actor Hidden In Game | obj:hide(), obj:show() |
| Set Actor Location | obj:move_to(x, y, z) |
| On Component Begin Overlap | obj:on_enter(function(player) ... end) |
| Realm Events: On Player Arrived | vrr.on_player_join(function(player) ... end) |
| Call a custom event on another Blueprint | obj:call("Event") (this machine), obj:tell_everyone("Event") (all) |
Testing
- In the Creator Kit's Play, objects, timers, zones and
vrr.logwork, and errors show in the Output Log (Window, Output Log) as yellowLogVRRScriptlines. - Commands about players (messages, points, joins, seats, animations, hands, input) need the game around them: Build, then Play Map in the Workshop panel runs your world in VR Realms itself.
- Scripts do not run on the standalone headsets yet, so a world's Steam Frame and Quest copy plays without its scripts. Keep anything the world cannot work without in Blueprints for now, or tell headset players in the description.
vrr.log("...")andprint(...)are the quickest way to see what a script is doing.
Build a game: collect the coins
A whole game from an empty level: coins lie around, walking into one takes it, the first to more than half of them wins, and a new round starts by itself.
- Make a coin. A Blueprint actor with a mesh (a flattened cylinder is fine) and a Sphere Collision a bit bigger than the mesh. On the sphere, tick Generate Overlap Events. On the actor, tick Replicates, so a hidden coin is hidden for everyone.
- Tag it. In the actor's Details, under Actor, Tags, add
Coin. - Place ten of them around your level (Alt + drag copies one).
- Add the script. Drop in a VR Realms Script actor, keep Run On on Host only (the host keeps the score for everyone), open the script window and click A complete game: collect the coins in the Starter scripts, or paste it:
local coins = world.find_all("Coin")
if #coins == 0 then
vrr.log("No actors tagged Coin in this level")
return
end
local to_win = math.floor(#coins / 2) + 1 -- more than half of them
local playing = false
local function new_round()
for _, coin in ipairs(coins) do coin:show() end
for _, p in ipairs(vrr.players()) do p:set_points(0) end
playing = true
vrr.announce("New round: collect " .. to_win .. " coins!", 4)
end
for _, coin in ipairs(coins) do
coin:on_enter(function(player)
if not playing then return end
coin:hide() -- hidden also means no collision, so it counts once
local total = player:add_points(1)
player:say("Coins: " .. total .. " / " .. to_win, 2)
if total >= to_win then
playing = false
vrr.announce(player.name .. " wins the coin hunt!", 6)
vrr.after(10, new_round)
end
end)
end
vrr.on_player_join(function(player)
player:say("Collect " .. to_win .. " coins to win!", 5)
end)
new_round()
- Test it. In the kit's Play you can already see the coins and errors in the Output Log, but players, points and messages need the game: use Play Map in the panel, which runs your built map in the real game (see Build a Map).
How it works: world.find_all("Coin") gives every coin once at the start. Each coin gets an on_enter zone, which hears the player who walked in. Hiding a coin also turns off its collision, so the same coin cannot count twice. Points are the world's own scoreboard, which every player already sees. vrr.after(10, new_round) waits ten seconds and then shows every coin again and sets the points back to zero.
Ideas to take it further: a sound or a sparkle when a coin is taken (coin:tell_everyone("Taken") to a custom event on the coin Blueprint), a time limit with vrr.every(1, ...), or coins that move to a new spot instead of hiding (coin:move_to(x, y, z)).
When something goes wrong
Errors show on the host's screen in the game (the first five, while Show Errors To Host is ticked) and always in the log. In the kit, open Window, Output Log: script errors are yellow LogVRRScript lines and your own vrr.log lines start with [Script. Type Script into the log's search box to see only those.
| You see | What it means | What to do |
|---|---|---|
attempt to index a nil value (local 'gate') | You used something that is not there. Most often world.find found no actor with that tag. | Check the tag in the actor's Details (tags are case-sensitive). Players and things a player is holding are never found. Guard it: if gate then ... end. |
attempt to call a nil value (method 'sya') | A command with that name does not exist: usually a typo. | Check the spelling against this page, or click the command in the script window's list. |
'end' expected (to close 'function' at line 3) near <eof> | A function, if, for or while has no end. | The script window shows the line while you type. Every block needs its own end. |
call: 'BP_Panel_C_0' has no custom event called 'ShowText' | The Blueprint has no custom event with exactly that name. | Use a Custom Event node (not a function) and the same spelling in both places. |
call: 'X' lives outside the Workshop folder | The event belongs to a Blueprint that is not part of your item, such as one of the engine's. | Only custom events of your own Blueprints can be called. |
the script was stopped: it ran too long without stopping | A loop that never ends, or more than about 2 million steps in one frame. | Give every while a way out. Spread big jobs over time with vrr.every. A stopped script stays stopped until the world starts again. |
the script was stopped: it took too long in one frame | The same, measured in time (a quarter of a second). | The same fixes. Very long texts make every step slower. |
the script was stopped: it used too much memory | The script held more than 16 MB. | Do not keep everything forever: set tables you no longer need to nil, and keep texts short. |
this text pattern takes too long | A text pattern with many .- or * over a long text. | Make the pattern simpler, or search a shorter piece of text. |
too many timers at once (at most 64) | Timers that are never cancelled pile up. | Keep the id from vrr.every and vrr.cancel(id) it when you are done. |
__gc is not allowed in VR Realms scripts | A metatable with a __gc field. | Clean up yourself instead, for example when a round ends. |
Nothing happens and there is no error?
- In the kit: commands about players (messages, points, joins, seats, animations) do nothing there. Use Play Map.
- Only the host sees it: tick Replicates on the object you hide or move.
set_textchanges the text on the machine running the script only. - A zone never fires: its collision needs Generate Overlap Events, and it must be big enough for a body to walk into.
- Commands stop working for a moment: you hit a rate limit (see below). Commands give back
falsewhen you send too many too fast. - Run On: a Host only script runs once, on the host. For something each player sees on their own machine (
vrr.me(), input, saved text), use Every player's machine.
Every node in Lua
All the nodes of the VR Realms category, grouped as on the Nodes page. player is a player you got from an event or from vrr.players(); obj is something from world.find. Parts in [square brackets] can be left out.
Player
| Lua | Node | Runs | Note |
|---|---|---|---|
vrr.me() | Get Local Player | Any machine | The player at this machine. nil on a dedicated server. Use it in Every player's machine scripts. |
player:hand_position("left" | "right") | Get Player Hand | Any machine | Where the hand is ({x, y, z}). Desktop players have hands too: where the game holds them, not tracked, and not sent to other machines. To hold something, use obj:attach_to. |
player:head_position() | Get Player Head | Any machine | Where the head is. |
player:in_vr() | Is Player In VR | Any machine | |
player:on_desktop() | Is Player On Desktop | Any machine | |
player.name | Get Player Name | Any machine | A field, kept up to date. |
player:is_me() | Is My Player | Any machine | |
player:is_host() | Is Host | Any machine | |
player:position() | Get Player Location | Any machine | {x, y, z} in centimetres. |
player:rotation() | Get Player Rotation | Any machine | {pitch, yaw, roll}; yaw only matters. |
player:eye_height() | Get Player Eye Height | Any machine | |
player:velocity() | Get Player Velocity | Any machine | {x, y, z}, cm per second. |
player:on_ground() | Is Player Grounded | Any machine | |
obj:on_enter(function(player) ... end) | Which Player | Any machine | Zones already tell you which player walked in. |
obj:on_enter / obj:on_leave | Is Player Body | Any machine | Zones count each player once, by the body. |
player:is_talking() | Is Player Talking | Any machine | |
player:loudness() | Get Player Loudness | Any machine | 0 to 1. |
player:avatar_id() | Get Player Avatar Id | Any machine | The Workshop id, as text (it is bigger than Lua numbers like). |
player:sit(obj [, part]) | Seat Player | Host | part = a component name or component tag on obj; the object's root if left out. |
player:stand_up([obj, part]) | Unseat Player | Host | Where they step out. |
player:move_to(x, y, z [, yaw]) | Move Player To | Host | |
player:send_to_spawn() | Send Player To Spawn | Host | |
player:say(text [, seconds]) | Show Message To Player | Host | Same as vrr.say(player, text). |
player:is_here() | Lua only | Any machine, reaches the host | False once they left: check before using a player you kept. |
Animation
| Lua | Node | Runs | Note |
|---|---|---|---|
player:play_animation("/Game/...", [rate, blend]) | Play Animation On Player | Host | Path of an animation in your world (right-click it, Copy Reference, keep the part in quotes). |
player:stop_animation([blend]) | Stop Player Animation | Host | |
player:is_animating() | Is Player Animating | Any machine | |
player:play_upper_body("/Game/...", [rate, blend, loops]) | Play Upper Body Animation On Player | Any machine | Arms only, they can keep walking. |
player:stop_upper_body([blend]) | Stop Upper Body Animation On Player | Any machine |
Points and labels
| Lua | Node | Runs | Note |
|---|---|---|---|
player:add_points(n) | Add Player Points | Host | Gives back the new total. The world's own scoreboard, not gold. |
player:set_points(n) | Set Player Points | Host | |
player:points() | Get Player Points | Any machine | |
player:label(key, value) | Set Player Label | Host | Any text per player: a team, a role. An empty value removes it. |
player:get_label(key) | Get Player Label | Any machine | |
player:clear_labels() | Clear Player Labels | Host |
The realm
| Lua | Node | Runs | Note |
|---|---|---|---|
vrr.players() | Get Players In Realm | Any machine | A list; vrr.player_count() for how many. |
vrr.host() | Get Host | Any machine | |
vrr.announce(text [, seconds]) | Show Message To Everyone | Host | |
vrr.chat(text) | Post Chat Line | Host | |
vrr.fire_channel(name) | Fire Channel | Host | The same channels VRSend / VRWhen tags use. |
obj:tell_host(event [, text, number]) | Tell Host | Any machine, reaches the host | Runs a custom event on a Blueprint of yours, on the host. |
obj:tell_everyone(event [, text, number]) | Tell Everyone | Any machine, reaches the host | The same, on every machine. |
world.find_link(link) | Find Item By Link | Any machine | An item placed with a Link name. |
screen:play(url) | Play On Screen | Any machine, reaches the host | http(s) links only. |
screen:stop() | Stop Screen | Any machine, reaches the host | |
screen:pause([true | false]) | Pause Screen | Any machine, reaches the host | |
screen:is_playing() | Is Screen Playing | Any machine | |
vrr.fade_out() | Fade Screen To Black | Any machine | This machine only. |
vrr.fade_in() | Fade Screen In | Any machine | |
vrr.language() | Get My Language | Any machine | "en", "de", ... |
Input
| Lua | Node | Runs | Note |
|---|---|---|---|
player:is_held(action) | Is Action Held | Any machine | Actions: Fire, FireLeft, Grab, GrabLeft, Jump, Crouch, Sprint, Interact, Menu, Aim, ButtonB, ButtonY, StickLeft, StickRight. |
player:axis("Move" | "Look") | Get Input Axis | Any machine | {x, y}, each -1 to 1. |
player:amount(action) | Get Action Amount | Any machine | How far a trigger is pulled. |
player:held_seconds(action) | Get Action Held Seconds | Any machine | |
player:action_label(action) | Get Action Label | Any machine | What the button is called on their device. |
player:start_controlling([movement_only]) | Start Controlling | Any machine, reaches the host | Their input drives your thing; Menu gives it back. |
player:stop_controlling() | Stop Controlling | Any machine, reaches the host | |
player:is_controlling() | Is Controlling | Any machine, reaches the host | |
player:vibrate([hand, strength, seconds]) | Vibrate Controller | Any machine, reaches the host |
Dares and saved text
| Lua | Node | Runs | Note |
|---|---|---|---|
player:complete_dare(id) | Complete Dare | Any machine | |
vrr.save(slot, text) | Save Text | Any machine | Kept on this player's PC, per world. |
vrr.load(slot) | Load Saved Text | Any machine | "" when nothing was saved. |
Events
The Realm Events and Realm Input Events components, as functions you hand over. Add as many as you like; each one runs.
| Lua | Blueprint event | Note |
|---|---|---|
vrr.on_player_join(function(player) end) | On Player Arrived | |
vrr.on_player_leave(function(player) end) | On Player Departed | player.name still works. |
vrr.on_points_changed(function(player, total) end) | On Points Changed | |
vrr.on_chat(function(player, text) end) | On Chat Message | |
vrr.on_channel(function(name) end) | On Channel | |
vrr.on_match_won(function(winner) end) | On Match Won | The built-in game modes. |
vrr.on_match_reset(function() end) | On Match Reset | |
vrr.on_action(function(player, action, pressed) end) | On Player Action | This machine's player only. |
vrr.on_animation_finished(function(player, path) end) | On Player Animation Finished | |
vrr.on_gesture(function(player, action, kind) end) | On Player Action Tap / Hold / Double Tap | kind = "tap", "hold" or "double". |
vrr.on_controlling(function(player, on) end) | On Player Controlling Changed | |
vrr.on_control_action(function(player, action, pressed) end) | On Control Action | Host only. |
Timers, objects, zones
| Lua | What it does |
|---|---|
vrr.after(seconds, fn) | Run fn once, later. Gives back an id. |
vrr.every(seconds, fn) | Run fn again and again. vrr.cancel(id) stops it. At most 64 timers. |
vrr.time() | Seconds since the world started. |
vrr.log(...) / print(...) | Writes to the log (the Output Log while you test). |
vrr.is_host_copy() | True in the host's copy of an Every player's machine script. |
world.find(tag) | The first object with that actor tag, or nil. |
world.find_all(tag) | Every object with that tag (up to 500). |
obj:show() / obj:hide() | Hidden also means no collision. Tick Replicates on the object so everyone sees it. |
obj:move_to(x, y, z) | Teleports it. Replicates + Replicate Movement for everyone to see. |
obj:turn_to(pitch, yaw, roll) | |
obj:position() | {x, y, z} |
obj:set_text(text) | The object's Text Render component, on the machine that runs the script only (a Text Render is not networked). For everyone, use an Every player's machine script, or a Blueprint event with tell_everyone. |
obj:on_enter(fn) / obj:on_leave(fn) | A zone: give the object a collision box with Generate Overlap Events on. fn gets the player. At most 64 zones. |
obj:attach_to(player, "left" | "right" | "head") | Snaps it onto a hand or the head (a desktop player's hands are where the game holds them; others do not see them). obj:detach() lets go. |
obj:call(event [, text, number]) | Runs one of your Blueprint's custom events on THIS machine only: nothing goes over the network. For a widget, a sound or an effect one player should see. Inputs by name, like Tell Host: Sender (this machine's player), Text, Number. |
More commands: API levels 2 to 6
A script can also look around, use your Blueprints' functions, play effects and sounds, make things, shoot, show panels, keep money and scores, and talk between its copies. These commands came in steps, called API levels. vrr.api is the level of the game a player runs, and vrr.has("name") says whether one command is there. A player with an older VR Realms does not have the newer ones, so start a script that needs them like this:
if not vrr.api or vrr.api < 2 then vrr.on_player_join(function(p) p:say("This world needs the latest VR Realms. Update in Steam.", 8) end) return end
| API level | What it adds | Where it is |
|---|---|---|
| 2 | Looking around, your Blueprints' own functions, effects and sounds, making things, shots, panels in the world, grabbing, messages between a script's copies. | In the game and the Creator Kit now |
| 3 | Map money: a currency of your own for one session, weapon pad prices, Buy spots. | In the game and the Creator Kit now |
| 4 | Sounds you keep: stop, fade, pause a sound and read how far it has played (to keep things in step with music). | Next update |
| 5 | Panels in the game's own card look: vrr.panel{ style = "card" }. | Next update |
| 6 | Saved tables and best scores for a player, and standing in place (no stick walking in a headset). | Next update |
A command that cannot do its job gives back nil and the reason, so you can see why: local fx, why = vrr.effect("FX_Sparks", pos). Effects, sounds and spawned Blueprints come from a VR Realms Script Assets actor in your level: a script can only use what you listed there. Where says which copy may call a command: Any = any copy, on that machine; Host = the host's copy, for everyone; Mine = this machine's own player.
Versions
| Lua | Where | What it does |
|---|---|---|
vrr.api | Any | 2 in a game with these commands; nil in an older game. Start a level-2 script with: if not vrr.api or vrr.api < 2 then vrr.on_player_join(function(p) p:say("This world needs the latest VR Realms. Update in Steam.", 8) end) return end (a message at the very start reaches nobody: no player is in yet) |
vrr.has(name) | Any | True if this game knows a command: vrr.has("trace"), vrr.has("obj:fn"). |
vrr.stats() | Any | What the script uses right now: steps (this frame), tick_steps, ticks, ticks_skipped, traces, effects, sounds, spawned, spawned_local, projectiles, panels, timers, refused, memory_kb. |
Every frame
| Lua | Where | What it does |
|---|---|---|
vrr.on_tick(function(dt) end [, hz]) | Any | Runs fn hz times a second (1 to 30 in a Host only script, 1 to 60 in an Every player's machine script; 30 if left out). dt = seconds since it last ran. Gives back an id: vrr.cancel(id). At most 8. All tick functions of a frame share 100,000 Lua steps: past that the rest wait a frame, and one that goes over in 120 frames in a row is cancelled (the script keeps running). |
The body and input
| Lua | Where | What it does |
|---|---|---|
player:head() | Any | {pos, rot, forward}: where the head (the camera, on a desktop) is and where it looks. |
player:hand("left" | "right") | Any | {pos, rot, forward, tracked}. tracked is false for a desktop player: the hand is where the game holds it, and other machines do not see it. |
player:stick("left" | "right") | Mine | {x, y}, -1 to 1. "left" = the walking stick (W A S D), "right" = the turning stick (also "move" / "look"). |
player:trigger("left" | "right") | Mine | 0 to 1. The mouse buttons on a desktop. |
player:grip("left" | "right") | Mine | 0 to 1. |
player:button(name) | Mine | true while held. "a", "b", "y", "trigger", "trigger_left", "grip", "grip_left", "stick_left", "stick_right", or any action name (Jump, Crouch, Interact, Action1 ...). The menu button is never readable. |
vrr.on_button(function(name, pressed) end) | Mine | This machine's player presses or lets go of a button (names as above). Every player's machine scripts only. |
Looking around
| Lua | Where | What it does |
|---|---|---|
vrr.trace(from, to [, {radius=, players=, ignore={obj, ...}}]) | Any | The first thing between two points: {pos, normal, distance, tag, obj, player}, or nil. 100 m at most. radius (0 to 50 cm) makes it a ball. players=true lets players stop it (hit.player). The game's own things answer with no tag and no obj. 32 a frame (a ball counts 4), 600 a second. |
Your Blueprints
| Lua | Where | What it does |
|---|---|---|
obj:fn("Lua_Name", ...) | Any | Runs a function or custom event of your Blueprint whose name starts with Lua_, on this machine, and gives back ok plus its outputs: local ok, n, text = door:fn("Lua_Open", 3). Inputs in order. Types: true/false, numbers, text, {x,y,z}, {pitch,yaw,roll}, {r,g,b,a}, objects and players, lists of those (256). Only Blueprints of your map's own folder. |
vrr.on_call(event, function(text, number, player, values) end) | Any | A Blueprint of your map called the Send To Script node (or Send To Script With Values: values is a list of text) on this Script actor's actor tag. |
vrr.publish(key, value) | Any | A value your Blueprints read with the Get Script Value node (a widget showing the score). 64 keys, 500 characters each. |
Effects and sounds
| Lua | Where | What it does |
|---|---|---|
vrr.effect(name, pos [, {rot=, scale=, on=obj|player, part=, life=}]) | Any | Plays a Niagara effect listed in your level's VR Realms Script Assets, on this machine. on= sticks it to an object (part = a component name or tag) or a player ("head", "left", "right"). life = seconds (60 at most). Gives back fx: fx:stop(). 24 alive (the oldest makes room), 40 a second. |
vrr.sound(name, pos [, {volume=, pitch=, on=, part=, start=}]) | Any | Plays a sound from Script Assets on this machine and gives back the sound (see Sounds you keep; an older game gives back true). start = seconds into the sound to begin at. 16 at once (when full, the oldest short sound makes room, so music keeps playing), 30 a second. |
vrr.effect_all(name, pos [, {rot=, scale=, life=}]) | Host | The host plays an effect on every machine (one network message). |
vrr.sound_all(name, pos [, {volume=, pitch=}]) | Host | The host plays a sound on every machine. |
Sounds you keep API level 4 Next update
Written and tested, not in the public game yet: these come with the next game and Creator Kit update. Ask before you use one: if vrr.has("stop") then ... end.
| Lua | Where | What it does |
|---|---|---|
snd:stop([fade]) | Any | Ends the sound (snd = what vrr.sound gave back). fade = seconds to fade out, 10 at most. Start a script that needs these with: if not vrr.api or vrr.api < 4 then ... end, or check type(snd) == "table". |
snd:time() | Any | Seconds into the sound right now, as the audio of the game plays it: the way to keep things in step with music. nil once the sound is over. |
snd:length() | Any | How long the sound is, in seconds. nil for a loop or a sound of unknown length. |
snd:playing() | Any | true while it plays (false when paused, stopped or over). |
snd:set_volume(volume [, fade]) | Any | 0 to 2, at once or over fade seconds. |
snd:pause() / snd:resume() | Any | Holds the sound where it is, and lets it go on. snd:time() stands still meanwhile. |
Making things
| Lua | Where | What it does |
|---|---|---|
world.spawn(name, pos [, {rot=, scale=, tag=, local_only=true}]) | Host | Makes a copy of a Blueprint actor listed in Script Assets and gives back its obj. For everyone it needs Replicates ticked in the Blueprint and the host's copy; local_only=true makes one only this machine sees (any copy). 200 alive (100 local), 20 a second. What a script made goes when the script stops or the world ends. |
obj:destroy() | Host | Removes it, with what this script attached to it. For everyone if it replicates and the host's copy does it. |
obj:set_transform{pos=, rot=, scale=} | Host | Any of the three. obj:scale() / obj:set_scale(s) / obj:rotation(). |
obj:attach_to(other_obj [, part] [, {offset_pos=, offset_rot=}]) | Host | Puts it on another object (part = a component name or tag). Without offsets it stays where it is; with them it snaps on, then moves by the offset. The same offsets work on a player: obj:attach_to(player, "right", {offset_pos={x=10,y=0,z=0}}). |
vrr.projectile{from=, dir=, speed=, gravity=, radius=, life=, look=, trail=, players=, on_hit=, on_end=} | Host | A shot that flies (speed up to 20,000 cm/s, gravity -2 to 4, life up to 10 s) and calls on_hit(hit) once, with the same table as vrr.trace. look = a Blueprint from Script Assets drawn as the shot, trail = an effect. The host's shot is drawn on every machine (hits are the host's). 64 in the air, 30 a second. p:stop(). |
Panels in the world
| Lua | Where | What it does |
|---|---|---|
vrr.panel{at=pos | obj | "follow", size={w=, h=}, face="player" | "fixed", color="#202020cc", style="card"} | Mine | A small screen in the world, on this machine only (use an Every player's machine script for one each). "follow" floats in front of the player. Size in cm. Gives back ui. 16 per script. Next update style="card" draws it as the game's own cards: an outline with corner brackets, a purple bar, the menu's fonts, a rule under the first big row of text, outlined buttons; a game before level 5 draws the plain panel. |
ui:text(text [, {size=, color=}]) | Mine | A row of text; gives back row: row:set("new text"). 12 rows a panel, 200 characters each. |
ui:bar(value [, {color=}]) | Mine | A bar from 0 to 1: bar:set(0.25). |
ui:button(text, function(player) end) | Mine | A button for the laser or the mouse. |
ui:move_to(pos) / ui:show() / ui:hide() / ui:destroy() | Mine | Updates of all panels: 30 a second. |
Grabbing
| Lua | Where | What it does |
|---|---|---|
vrr.on_grab(function(obj, player, hand) end) | Any | A player's hand took a grabbable (one made Grabbable in the Details panel). hand = "left" or "right". The host's copy hears every player; another machine's copy (Every player's machine) hears its own player only. Check with vrr.has("on_grab"). |
vrr.on_release(function(obj, player, velocity) end) | Any | The hand let go: velocity = {x, y, z} in cm/s just after (a throw, or the desktop power bar). |
obj:holder() | Any | The player holding it now, or nil (from these events). |
obj:position() / obj:rotation() / obj:scale() while held | Any | Readable while a player holds it (moving, hiding or destroying a held thing is still refused). |
Map money API level 3
| Lua | Where | What it does |
|---|---|---|
vrr.money_setup{name=, start=, max=} | Host | Gives the map its own money for this session ("Cash", "Coins"): everyone has start, at most max. Never gold, never saved. Or set Map money on Map settings and skip this. true, or nil + why (an older game, the Creator Kit editor). |
player:money() | Any | Their amount (0 without money). Any copy reads it. |
player:give_money(n [, reason]) | Host | Adds n (a negative n takes, never below 0). Gives back the new total. |
player:take_money(n [, reason]) | Host | Takes n only if they have it all: true, or false and nothing taken. The way to sell something. |
player:set_money(n) | Host | A new run: everyone back to the start amount. |
vrr.money_name() / vrr.has_money() | Any | The name of the money ("" without one), and whether the map has money. |
vrr.money_counter(false) | Mine | Your own panel shows the money, so the counter of the game (left wrist, top of the screen) hides on this machine. true brings it back. |
vrr.on_money(function(player, total, change, reason) end) | Host | The money of a player changed (reason: "kill", "buy", "pad", your own words). |
vrr.on_buy(function(player, spot, what, price) end) | Host | A player bought at a Buy spot (from the Realms page). spot = its zone, what = what it gives ("Script.<name>" for one made for your script). |
Saved tables, best scores, standing in place API level 6 Next update
Written and tested, not in the public game yet: these come with the next game and Creator Kit update. Ask before you use one: if vrr.has("save_table") then ... end.
| Lua | Where | What it does |
|---|---|---|
vrr.save_table(slot, table) | Mine | Keeps a table for this player in this world, on their PC (numbers, text, true/false and tables of those, 3 deep): a hero, settings, a bag. It is vrr.save with the writing done for you: the same 8 slots a world, 16 KB a slot. nil and a reason when it does not fit. |
vrr.load_table(slot) | Mine | The table vrr.save_table kept; an empty table when there is none. |
vrr.best(slot, name, score) | Mine | A best score: keeps the number under that name only when it is higher than the one kept. Gives back the best and true when this one is new. vrr.best(slot, name) only reads (nil when there is none). One slot holds many names (1 to 32 letters, digits, _ - .), as lines "name=number": the Blueprint nodes Save Best Score and Load Best Score share it. |
vrr.lock_move(true) | Mine | The player at this machine stands in place: in a headset the walk stick walks nowhere and the stick does not crouch (turning stays; a desktop player keeps their keys). false gives it back; so does the script stopping. For maps played on one spot (a workout, a ride): move the player with player:move_to from the host instead. nil and a reason in a game that cannot do it yet. |
Messages between copies
| Lua | Where | What it does |
|---|---|---|
vrr.send_host(name, data) | Any | From a player's copy to the host's copy of the same Script actor. data = nil, numbers, text, true/false, or tables of those (3 deep, 1000 characters once packed). The host must check it: anyone can send anything. |
vrr.send_all(name, data) | Host | From the host's copy to every machine's copy (an Every player's machine script). |
vrr.send_to(player, name, data) | Host | To one player's copy. Every machine receives it and only that player's runs it: never put a secret in a message. |
vrr.on_message(name, function(data, player) end) | Any | player = who sent it. Names: letters, digits, _ - . (not case sensitive). |
Examples
Each of these runs as it is. Copy one into a Script actor (or click it in the script window's list) and tag your level's objects as it says.
Say hello to everyone who arrives
Run On: Host only. The smallest useful script. It greets each player by name and tells the first one they are alone for now.
vrr.on_player_join(function(player)
player:say("Welcome, " .. player.name .. "!")
if vrr.player_count() == 1 then
player:say("You're the first one here. Invite a friend!", 6)
end
end)
vrr.on_player_leave(function(player)
vrr.announce(player.name .. " left the world")
end)
A gate only the red team can open
Run On: Host only. Tag a box with overlap events on as RedButton, and a gate mesh (Replicates ticked) as BigGate. A player label is how you mark teams.
local gate = world.find("BigGate")
local button = world.find("RedButton")
-- put everyone who joins on a team, taking turns
local next_team = "red"
vrr.on_player_join(function(player)
player:label("team", next_team)
player:say("You are on the " .. next_team .. " team")
if next_team == "red" then next_team = "blue" else next_team = "red" end
end)
button:on_enter(function(player)
if player:get_label("team") == "red" then
gate:hide()
player:say("The gate is open for 10 seconds")
vrr.after(10, function() gate:show() end)
else
player:say("Only the red team can open this gate")
end
end)
A race with a timer and a best time
Run On: Host only. Two zones tagged StartLine and FinishLine. The best time is kept for as long as the world is open, and the winner gets a scoreboard point.
local start, finish = world.find("StartLine"), world.find("FinishLine")
local started = {}
local best, best_name = nil, nil
start:on_enter(function(player)
started[player.id] = vrr.time()
player:say("Go!", 2)
end)
finish:on_enter(function(player)
local t0 = started[player.id]
if not t0 then return end -- they skipped the start line
started[player.id] = nil
local seconds = vrr.time() - t0
local text = string.format("%.2f", seconds)
if not best or seconds < best then
best, best_name = seconds, player.name
vrr.announce("New record: " .. player.name .. " in " .. text .. " s!")
player:add_points(1)
else
player:say("Your time: " .. text .. " s (record " .. string.format("%.2f", best) .. " by " .. best_name .. ")")
end
end)
King of the hill
Run On: Host only. A zone tagged Hill. Every second, each player standing on it gets a point. The first to 30 wins and the round starts over.
local hill = world.find("Hill")
local on_hill = {}
hill:on_enter(function(player) on_hill[player.id] = player end)
hill:on_leave(function(player) on_hill[player.id] = nil end)
vrr.every(1, function()
for id, player in pairs(on_hill) do
if player:is_here() then
if player:add_points(1) >= 30 then
vrr.announce(player.name .. " is the king of the hill!", 6)
for _, p in ipairs(vrr.players()) do p:set_points(0) end
vrr.fire_channel("HillWon") -- let a Blueprint play fireworks
end
else
on_hill[id] = nil
end
end
end)
Chat commands: !roll and !time
Run On: Host only. Reacts to public chat. Lua's math.random works as usual.
vrr.on_chat(function(player, text)
if text == "!roll" then
vrr.chat(player.name .. " rolled a " .. math.random(1, 6))
elseif text == "!time" then
vrr.chat("This world has been open for " .. math.floor(vrr.time() / 60) .. " minutes")
elseif text:sub(1, 5) == "!say " then
vrr.announce(player.name .. ": " .. text:sub(6))
end
end)
A countdown round that talks to your Blueprints
Run On: Host only. A Blueprint tagged RoundBoard has a Text Render and custom events RoundStarted and RoundOver. The script keeps time, the Blueprint does the show.
local board = world.find("RoundBoard")
local seconds_left = 0
local ticker
local function start_round()
seconds_left = 60
board:tell_everyone("RoundStarted", "", 60)
ticker = vrr.every(1, function()
seconds_left = seconds_left - 1
board:set_text(tostring(seconds_left))
if seconds_left <= 0 then
vrr.cancel(ticker)
board:tell_everyone("RoundOver")
vrr.announce("Round over! Next one in 15 seconds")
vrr.after(15, start_round)
end
end)
end
vrr.after(5, start_round)
A lantern in your hand
Run On: Every player's machine. Runs on every machine and uses vrr.me(): each machine puts the lantern (tagged Lantern) in its own player's left hand, so everyone sees it in their own hand. Desktop players have no hands, so it goes to the head.
local me = vrr.me()
if me then
local lanterns = world.find_all("Lantern")
local mine = lanterns[1]
if mine then
if me:in_vr() then
mine:attach_to(me, "left")
else
mine:attach_to(me, "head")
end
me:say("Your lantern is lit")
end
end
A cinema that starts when you sit down
Run On: Host only. A screen item placed with the link Cinema, a chair Blueprint tagged Chair with a scene component named Seat, and a zone tagged ChairZone.
local screen = world.find_link("Cinema")
local chair = world.find("Chair")
local zone = world.find("ChairZone")
zone:on_enter(function(player)
player:sit(chair, "Seat")
if not screen:is_playing() then
screen:play("https://www.youtube.com/watch?v=aqz-KE-bpKQ")
end
end)
vrr.on_player_leave(function()
if vrr.player_count() == 0 then screen:stop() end
end)
Hold to charge, let go to jump
Run On: Every player's machine. Input is known on the player's own machine. The longer you hold Interact, the stronger the buzz; a double tap of Jump plays a wave. Animations come from your world's own content by path.
vrr.on_gesture(function(player, action, kind)
if not player:is_me() then return end
if action == "Jump" and kind == "double" then
player:play_upper_body("/Game/MyWorld/Anims/Wave.Wave")
end
end)
vrr.every(0.25, function()
local me = vrr.me()
if me and me:is_held("Interact") then
local power = math.min(1, me:held_seconds("Interact") / 3)
me:vibrate("right", power, 0.25)
end
end)
A complete game: collect the coins
Run On: Host only. Every coin is an actor tagged Coin, with a collision box (Generate Overlap Events on) and Replicates ticked. Walk into a coin to take it; the first to more than half of them wins, and a new round starts 10 seconds later. The whole build is in "Build a game: collect the coins" above.
local coins = world.find_all("Coin")
if #coins == 0 then
vrr.log("No actors tagged Coin in this level")
return
end
local to_win = math.floor(#coins / 2) + 1 -- more than half of them
local playing = false
local function new_round()
for _, coin in ipairs(coins) do coin:show() end
for _, p in ipairs(vrr.players()) do p:set_points(0) end
playing = true
vrr.announce("New round: collect " .. to_win .. " coins!", 4)
end
for _, coin in ipairs(coins) do
coin:on_enter(function(player)
if not playing then return end
coin:hide() -- hidden also means no collision, so it counts once
local total = player:add_points(1)
player:say("Coins: " .. total .. " / " .. to_win, 2)
if total >= to_win then
playing = false
vrr.announce(player.name .. " wins the coin hunt!", 6)
vrr.after(10, new_round)
end
end)
end
vrr.on_player_join(function(player)
player:say("Collect " .. to_win .. " coins to win!", 5)
end)
new_round()
Show each player their own visits on a widget
Run On: Every player's machine. A Blueprint tagged VisitsPanel has a Widget Component and a custom event ShowText with inputs Text (String) and Number (Float) that puts the text on the widget (see "Showing text on a widget" above). The script runs on every machine and obj:call stays on that machine, so each person sees their own count.
local visits = tonumber(vrr.load("visits")) or 0
visits = visits + 1
vrr.save("visits", tostring(visits))
local panel = world.find("VisitsPanel")
if panel then
if visits == 1 then
panel:call("ShowText", "First time here? Have a look around!", visits)
else
panel:call("ShowText", "Welcome back! Visit number " .. visits, visits)
end
end
Remember a player between visits
Run On: Every player's machine. Saved text lives on the player's own PC, per world. Here it counts visits.
local visits = tonumber(vrr.load("visits")) or 0
visits = visits + 1
vrr.save("visits", tostring(visits))
local me = vrr.me()
if me then
if visits == 1 then
me:say("First time here? Have a look around!")
else
me:say("Welcome back! Visit number " .. visits)
end
end
A turret that shoots at targets
Run On: Host only. Tag the turret Turret and a few boxes Target. Put a small ball Blueprint (Replicates not needed, it is only drawn) called BP_Bolt and an effect FX_Pop in a VR Realms Script Assets actor. Hits give the closest player a point.
if not vrr.api or vrr.api < 2 then vrr.on_player_join(function(p) p:say("This world needs the latest VR Realms. Update in Steam.", 8) end) return end
local turret = world.find("Turret")
local targets = world.find_all("Target")
if not turret or #targets == 0 then vrr.log("Tag a Turret and some Target boxes") return end
local next_target = 1
vrr.every(1.5, function()
local target = targets[next_target]
next_target = next_target % #targets + 1
local from, to = turret:position(), target:position()
vrr.projectile{
from = { x = from.x, y = from.y, z = from.z + 120 },
dir = { x = to.x - from.x, y = to.y - from.y, z = to.z - from.z - 120 },
speed = 2500, gravity = 0.3, look = "BP_Bolt",
on_hit = function(hit)
vrr.effect_all("FX_Pop", hit.pos)
if hit.tag == "Target" and hit.obj then
hit.obj:hide()
vrr.after(3, function() hit.obj:show() end)
end
end,
}
end)
A door your Blueprint opens, with a score on a widget
Run On: Host only. Your door Blueprint (tag Door, Replicates ticked) has a function Lua_Open with a Boolean input Open and an Integer output Times. A box with overlap events on is tagged DoorButton. A widget shows the count with Get Script Value (tag the Script actor DoorScript).
if not vrr.api or vrr.api < 2 then vrr.on_player_join(function(p) p:say("This world needs the latest VR Realms. Update in Steam.", 8) end) return end
local door = world.find("Door")
local button = world.find("DoorButton")
if not door or not button then vrr.log("Tag a Door and a DoorButton") return end
local open = false
button:on_enter(function(player)
open = not open
local ok, times = door:fn("Lua_Open", open)
if not ok then vrr.log("Lua_Open: " .. tostring(times)) return end
vrr.publish("door_times", times)
player:say(open and "The door opens" or "The door closes")
end)
Waves on a panel for everyone
Run On: Every player's machine. Each machine builds its own panel; the host decides the wave and tells every copy with vrr.send_all.
if not vrr.api or vrr.api < 2 then vrr.on_player_join(function(p) p:say("This world needs the latest VR Realms. Update in Steam.", 8) end) return end
local ui = vrr.panel{ at = "follow", size = { w = 40, h = 14 } }
local title = ui and ui:text("Waiting for the host...", { size = 26 })
local bar = ui and ui:bar(0)
vrr.on_message("wave", function(data, sender)
if type(data) ~= "table" or type(data.n) ~= "number" then return end
if title then title:set("Wave " .. data.n) end
if bar then bar:set(data.n / 10) end
end)
if vrr.is_host_copy() then
local wave = 0
vrr.every(20, function()
wave = math.min(wave + 1, 10)
vrr.send_all("wave", { n = wave })
end)
end
Sparkles from your hand while you pull the trigger
Run On: Every player's machine. Reads this machine's own trigger and hand ten times a second. Put a short effect FX_Sparkle in Script Assets. Only you see your sparkles (vrr.effect plays on this machine).
if not vrr.api or vrr.api < 2 then vrr.on_player_join(function(p) p:say("This world needs the latest VR Realms. Update in Steam.", 8) end) return end
local me = vrr.me()
if not me then return end
vrr.on_tick(function(dt)
local pull = me:trigger("right")
if pull and pull > 0.5 then
local hand = me:hand("right")
if hand then vrr.effect("FX_Sparkle", hand.pos, { life = 0.6, scale = pull }) end
end
end, 10)
Ping the host and get an answer
Run On: Every player's machine. Press B: your copy asks the host's copy, which answers only you. Shows the three message commands and how the host checks what it gets.
if not vrr.api or vrr.api < 2 then vrr.on_player_join(function(p) p:say("This world needs the latest VR Realms. Update in Steam.", 8) end) return end
local sent_at = 0
vrr.on_button(function(name, pressed)
if name == "b" and pressed then
sent_at = vrr.time()
vrr.send_host("ping", { at = sent_at })
end
end)
vrr.on_message("ping", function(data, sender)
-- only the host's copy gets "ping"; anyone can send anything, so check it
if not vrr.is_host_copy() or not sender or type(data) ~= "table" then return end
vrr.send_to(sender, "pong", { players = vrr.player_count() })
end)
vrr.on_message("pong", function(data)
local me = vrr.me()
if me and type(data) == "table" then
me:say(string.format("Pong! %.0f ms, %d players here", (vrr.time() - sent_at) * 1000, data.players or 0))
end
end)
What a script cannot do
- No files, no web, no other programs, no console commands, and no calling engine functions by name. A script only has plain Lua and the commands on this page.
- A script that runs too long without coming back (about 2 million steps, or a quarter of a second, in one frame, all its events and timers together) or holds more than 16 MB of memory is stopped for good with an error, instead of freezing everyone's game. pcall cannot catch that stop.
- Text patterns (string.find, match, gmatch, gsub) have a work limit too: a pattern that would take very long gives an error instead.
- Not available:
__gcin metatables,string.dump, and the collector's controls (collectgarbage("count")still works). - Messages and chat lines: at most 10 at once, one more each second. Commands that reach other players (points, labels, moving things, Blueprint events, animations and so on): 60 at once, 20 more each second. Screens: a new link every two seconds. Saved text: 10 at once, one more each second. Timers and zones: 64 each. One script: 65,536 characters.
- Players cannot be moved, hidden or found as objects, only through their own commands.
- Precompiled Lua is refused: scripts are always plain text, so anyone can read what a world does.