DataModel

Show Deprecated
Not Creatable

The DataModel (commonly known as game after the global variable used to access it) is the root of Roblox's parent-child hierarchy. Its direct children are services (such as the Workspace and Lighting) that act as the fundamental components of a Roblox game.

Code Samples

DataModel

1game:GetService("Workspace").Part:Destroy() -- 'game' is a reference to the DataModel

Summary

Properties

Describes the ID of the user or group that owns the place.

READ ONLY
NOT REPLICATED

Describes the CreatorType of the place, whether the place is owned by a user or a group.

READ ONLY
NOT REPLICATED

Describes the ID of the experience that the place running on the server belongs to.

READ ONLY
NOT REPLICATED

Not functional. Historically described the Genre of the place as set on the Roblox website.

READ ONLY
NOT REPLICATED
HIDDEN
READ ONLY
NOT REPLICATED

A unique identifier for the running game server instance.

READ ONLY
NOT REPLICATED

Describes the ID of the place running on the server.

READ ONLY
NOT REPLICATED

Describes the version of the place the server is running on.

READ ONLY
NOT REPLICATED

Describes the private server ID of the server, if the server is a private server or a reserved server.

READ ONLY
NOT REPLICATED

Describes the UserId of the Player that owns the private server if the server is private.

READ ONLY
NOT REPLICATED

A reference to the Workspace service.

READ ONLY
NOT REPLICATED

Events


Fires when the user prompts and increase or decrease in graphics quality using the hotkeys.


Fires on the client when the game finishes loading for the first time.

ScreenshotSavedToAlbum(filename: string, success: boolean, message: string): RBXScriptSignal  


Methods

BindToClose(function: function): void  

Binds a function to be called before the game shuts down.

DefineFastFlag(name: string, defaultValue: boolean): boolean  


DefineFastInt(name: string, defaultValue: number): number  


DefineFastString(name: string, defaultValue: string): string  



Checks the availability of various engine features.


Returns a table containing basic information about the jobs performed by the task scheduler.


Returns an array of Instances associated with the given content URL.


Returns true if the client has finished loading the game for the first time.

Load(url: Content): void  

Loads a Roblox Place File from a URL.

OpenVideosFolder(): void  


ReportInGoogleAnalytics(category: string, action: string, label: string, value: number): void  


SetFastIntForTesting(name: string, newValue: number): number  


SetPlaceId(placeId: number): void  

Sets the DataModel.PlaceId of the current game instance to the given placeId.

SetUniverseId(universeId: number): void  

Sets the DataModel.GameId of the current game instance to the given universeId.

Shutdown(): void  

Shuts down the current game instance.

HttpGetAsync(url: string, httpRequestType: HttpRequestType): string  YIELDS


HttpPostAsync(url: string, data: string, contentType: string, httpRequestType: HttpRequestType): string  YIELDS


Properties

CreatorId

Read Only
Not Replicated

This property describes the ID of the user or group that owns the place. If the DataModel.CreatorType property is 'User' then CreatorId will be the Player.UserId of the place's owner. If the DataModel.CreatorType is 'Group' then CreatorId will be the ID of the group that owns the place.

CreatorType

Read Only
Not Replicated

This property describes the CreatorType of the place, whether the place is owned by a user or a group.

If the CreatorType is 'User', then the DataModel.CreatorId property will describe the UserId of the account that owns the game. If the CreatorType is 'Group', then it will describe the group ID.

GameId

Read Only
Not Replicated

This property describes the ID of the experience that the place running on the server belongs to.

This ID can be found in the top right corner of the Asset Manager in Roblox Studio. When using Roblox Studio, if the place has not been published to Roblox then the GameId will correspond with the template being used.

See also:

Genre

Read Only
Not Replicated

This property is broken and should not be used.

This property historically described the Genre of the place as set on the Roblox website.

This property, along with DataModel.GearGenreSetting, no longer functions correctly due to genres existing on the Roblox website that are not reflected in the Genre enum. As a result, attempting to read this property may throw an error.

IsSFFlagsLoaded

Hidden
Read Only
Not Replicated

JobId

Read Only
Not Replicated

This property is a unique identifier for the running game server instance.

The JobId is a universally unique identifier (UUID) meaning that no two servers, past or present, will ever have the same JobId.

JobId defaults to an empty string in Roblox Studio.

See also:

PlaceId

Read Only
Not Replicated

This property describes the ID of the place running on the server.

This ID corresponds with the number in the place's URL. For example, the ID of the place at the following URL is 1818:

The place ID can also be found in the Asset Manager in Roblox Studio by right clicking on the place inside of the Places folder and selecting 'Copy ID to clipboard'.

When using Roblox Studio, if the place has not been published to Roblox then the PlaceId will correspond with the template being used.

See also:

  • DataModel.GameId, which describes the ID of the experience that the current place belongs to
  • DataModel.JobId, which is a unique identifier for the server game instance running
  • TeleportService, which is a service that can be used to transport Players between places

PlaceVersion

Read Only
Not Replicated

This property describes the version of the place the server is running on.

This version number corresponds with the version number shown under the Version History section of the place's settings. It is not the current version of the Roblox client.

In Roblox Studio, this property is set to 0.

When a server instance is created for a place, it uses the place's current version. If the place is later updated while this server is running, the server will remain at its current version.

This property can be used to display a ScreenGui showing the current version of the game to Players to assist with debugging.

PrivateServerId

Read Only
Not Replicated

This property describes the private server ID of the server, if the server is a private server.

If the server is not a private server, then this property will be an empty string.

Private servers

Private servers refer to the following:

PrivateServerId vs JobId

The PrivateServerId of a server is different from the DataModel.JobId. The JobId is the unique identifier of the current server instance.

Private servers (private or reserved servers) can have multiple server instances associated with them over time. This is because, although only one server instance can be running at once for a private server, new server instances can open and close as players join and leave the game. For example, no server instance is running when nobody is playing in the server. The PrivateServerId will be consistent across all of these server instances, and the DataModel.JobId will be unique for each once.

See also:

PrivateServerOwnerId

Read Only
Not Replicated

This property describes the UserId of the Player that owns the private server if the server is private.

If the server is a standard or reserved server then this property will be set to 0.

This property could be used to identify if a Player is the owner of the private server, for example:


1local Players = game:GetService("Players")
2
3-- is this a private server?
4if game.PrivateServerId ~= "" and game.PrivateServerOwnerId ~= 0 then
5
6 -- listen for new players being added
7 Players.PlayerAdded:Connect(function(player)
8
9 -- check if the player is the server owner
10 if player.UserId == game.PrivateServerOwnerId then
11 print("The private server owner has joined the game")
12 end
13 end)
14end
15

See also:

Workspace

Read Only
Not Replicated

The Workspace property is a reference to the Workspace service.

This property will always point to the Workspace and will never be nil.

The Workspace can also be accessed using the global variable workspace and the ServiceProvider:GetService() function. For example:


1workspace -- a global variable
2game.Workspace -- a property of the DataModel (game)
3game:GetService("Workspace") -- workspace is a service
4

Events

GraphicsQualityChangeRequest

Fires when the user prompts an increase or decrease in graphics quality using the hotkeys.

This event fires under the following conditions:

  • If the user presses F10, this event fires with a betterQuality argument of true
  • If the user presses Shift + F10, this event fires with a betterQuality argument of false

GraphicsQualityChangeRequest does not provide the current graphics quality level or cover all updates to the graphics quality. For example, changes made in the core GUI escape menu are not registered. This event is intended to be used by Roblox Core Scripts to update the graphics quality and display notifications.

You can retrieve a user's SavedQualitySetting using UserGameSettings with the following snippet:


1UserSettings():GetService("UserGameSettings").SavedQualityLevel
2

If the user's graphics settings are set to automatic then the SavedQualitySetting will be 'Automatic'. There is currently no way for developers to reliably get the current graphics quality level of a user's machine.

Parameters

betterQuality: boolean

Whether the user has prompted an increase (true) or a decrease (false) in graphics quality.


Code Samples

Handling User Changes in Graphics Quality

1game.GraphicsQualityChangeRequest:Connect(function(betterQuality)
2 if betterQuality then
3 print("The user has requested an increase in graphics quality!")
4 else
5 print("The user has requested a decrease in graphics quality!")
6 end
7end)

Loaded

This event fires on the client when the game finishes loading for the first time.

The Loaded event fires when all initial Instances in the game have finished replicating to the client.

Unless they are parented to ReplicatedFirst, LocalScripts will not run prior to this event firing. The following snippet, ran from a LocalScript in ReplicatedFirst, will yield until the game has loaded:


1if not game:IsLoaded() then
2 game.Loaded:Wait()
3end
4

See also:


ScreenshotReady

Roblox Script Security

Parameters

path: string

ScreenshotSavedToAlbum

Roblox Script Security

Parameters

filename: string
success: boolean
message: string

Methods

BindToClose

void

This function binds a function to be called prior to the game shutting down.

Multiple functions can be bound using BindToClose if it is called repeatedly. The game will wait a maximum of 30 seconds for all bound functions to complete running before shutting down. After 30 seconds, the game will shut down regardless if all bound functions have completed or not.

Bound functions will be called in parallel, meaning they will run at the same time.

You are advised to use RunService:IsStudio() to verify the current session is not Roblox Studio. If this is not done, all bound functions will be required to complete in offline testing sessions.

When using the DataStoreService, best practice is to bind a function saving all unsaved data to DataStores using BindToClose. Otherwise, data may be lost if the game shuts down unexpectedly. For an example of this, refer to the code samples.

See also:

Parameters

function: function

A function to be called prior to the game shutting down.


Returns

void

Code Samples

Binding to and Handling Game Shutdown

1game:BindToClose(function()
2 print(2 * 2)
3 task.wait(3)
4 print("Done")
5end)
Saving player data before shutting down

1local DataStoreService = game:GetService("DataStoreService")
2local RunService = game:GetService("RunService")
3
4local playerDataStore = DataStoreService:GetDataStore("PlayerData")
5
6local allPlayerSessionDataCache = {}
7
8local function savePlayerDataAsync(userId, data)
9 return playerDataStore:UpdateAsync(userId, function(oldData)
10 return data
11 end)
12end
13
14local function onServerShutdown()
15 if RunService:IsStudio() then
16 -- Avoid writing studio data to production and stalling test session closing
17 return
18 end
19
20 -- Reference for yielding and resuming later
21 local mainThread = coroutine.running()
22
23 -- Counts up for each new thread, down when the thread finishes. When 0 is reached,
24 -- the individual thread knows it's the last thread to finish and should resume the main thread
25 local numThreadsRunning = 0
26
27 -- Calling this function later starts on a new thread because of coroutine.wrap
28 local startSaveThread = coroutine.wrap(function(userId, sessionData)
29 -- Perform the save operation
30 local success, result = pcall(savePlayerDataAsync, userId, sessionData)
31 if not success then
32 -- Could implement a retry
33 warn(string.format("Failed to save %d's data: %s", userId, result))
34 end
35
36 -- Thread finished, decrement counter
37 numThreadsRunning -= 1
38
39 if numThreadsRunning == 0 then
40 -- This was the last thread to finish, resume main thread
41 coroutine.resume(mainThread)
42 end
43 end)
44
45 -- This assumes playerData gets cleared from the data table during a final save on PlayerRemoving,
46 -- so this is iterating over all the data of players still in the game that hasn't been saved
47 for userId, sessionData in pairs(allPlayerSessionDataCache) do
48 numThreadsRunning += 1
49
50 -- This loop finishes running and counting numThreadsRunning before any of
51 -- the save threads start because coroutine.wrap has built-in deferral on start
52 startSaveThread(userId, sessionData)
53 end
54
55 if numThreadsRunning > 0 then
56 -- Stall shutdown until save threads finish. Resumed by the last save thread when it finishes
57 coroutine.yield()
58 end
59end
60
61game:BindToClose(onServerShutdown)

DefineFastFlag

Roblox Script Security

Parameters

name: string
defaultValue: boolean

Returns

DefineFastInt

Roblox Script Security

Parameters

name: string
defaultValue: number

Returns

DefineFastString

Roblox Script Security

Parameters

name: string
defaultValue: string

Returns

GetEngineFeature

Local User Security

The goal of this API is to provide a stable interface for core script-level Lua code to query for enabled engine features.

If a feature does not exist, this method returns false. This is intended for the case where new Lua is running on an old engine version.

Example:


1if game:GetEngineFeature("FooApi") then
2 -- code using Foo
3end
4

Parameters

name: string

Returns

GetFastFlag

Local User Security

Parameters

name: string

Returns

GetFastInt

Local User Security

Parameters

name: string

Returns

GetFastString

Local User Security

Parameters

name: string

Returns

GetJobsInfo

Plugin Security

Returns a table containing basic information about the jobs performed by the task scheduler.

In computing, a task scheduler is a system responsible for executing key tasks at the appropriate intervals.

You can also find live task scheduler statistics in the Task Scheduler window in Roblox Studio.

The first entry in the table returned is a reference dictionary containing the statistics (or headings) available. It is in the following format:


1{
2 ["name"] = "name",
3 ["averageDutyCycle"] = "averageDutyCycle",
4 ["averageStepsPerSecond"] = "averageStepsPerSecond",
5 ["averageStepTime"] = "averageStepTime",
6 ["averageError"] = "averageError",
7 ["isRunning"] = "isRunning",
8}
9

The subsequent entries in the table returned are dictionaries containing the above statistics for jobs performed by the task scheduler. For example:


1{
2 ["name"] = "Heartbeat",
3 ["averageDutyCycle"] = 0,
4 ["averageStepsPerSecond"] = 0,
5 ["averageStepTime"] = 0,
6 ["averageError"] = 0,
7 ["isRunning"] = false,
8}
9

See also:


Returns

A table containing information about the jobs performed by the task scheduler, see above for the format.

Code Samples

Getting Jobs Info

1local jobInfo = game:GetJobsInfo()
2local jobTitles = jobInfo[1]
3
4table.remove(jobInfo, 1)
5
6local divider = string.rep("-", 120)
7print(divider)
8warn("JOB INFO:")
9print(divider)
10
11for _, job in pairs(jobInfo) do
12 for jobIndex, jobValue in pairs(job) do
13 local jobTitle = jobTitles[jobIndex]
14 warn(jobTitle, "=", jobValue)
15 end
16 print(divider)
17end

GetObjects

Plugin Security

This function returns an array of Instances associated with the given content URL.

This function can be used to insert content from the Roblox library, such as:

  • Models
  • Decals
  • Meshes
  • Plugins
  • Animations

It is not possible to insert Sounds using this method as they do not have an Instance associated with them and have only a content URL.

Unlike InsertService:LoadAsset(), GetObjects does not require an asset to be 'trusted'. This means that an asset does not need to be owned by the logged in user, or created by Roblox, to be inserted. However, if the asset is not owned by the logged in user it must be freely available.

Due to this function's security context it can only be used by plugins or the command bar. For an alternative that can be used in Scripts and LocalScripts, see InsertService:LoadAsset().

Parameters

url: Content

The given content URL.


Returns

An array of Instances associated with the content URL.

Code Samples

View a plugin's source code

1local Selection = game:GetService("Selection")
2
3local WEB_URL = "plugin URL here"
4
5local function downloadPlugin(webURL)
6 -- get the content URL
7 local contentID = string.match(webURL, "%d+")
8 local contentURL = "rbxassetid://" .. contentID
9
10 -- download the objects
11 local objects = game:GetObjects(contentURL)
12
13 -- decide where to parent them
14 local selection = Selection:Get()
15 local parent = #selection == 1 and selection[1] or workspace
16
17 -- parent the objects
18 for _, object in pairs(objects) do
19 object.Parent = parent
20 end
21end
22
23downloadPlugin(WEB_URL)
Batch convert decal IDs

1local IMAGES = {
2 -- Insert Decal web URLs in an array here (as strings)
3}
4
5-- open the dictionary
6local outputString = "textures = {"
7
8-- utility function to add a new entry to the dictionary (as a string)
9local function addEntryToDictionary(original, new)
10 outputString = outputString
11 .. "\n" -- new line
12 .. " " -- indent
13 .. '["'
14 .. original
15 .. '"]' -- key
16 .. ' = "'
17 .. new
18 .. '",' -- value
19end
20
21print("Starting conversion")
22
23for _, webURL in pairs(IMAGES) do
24 -- get the content URL
25 local contentID = string.match(webURL, "%d+")
26 local contentURL = "rbxassetid://" .. contentID
27
28 local success, result = pcall(function()
29 local objects = game:GetObjects(contentURL)
30 return objects[1].Texture
31 end)
32
33 if success then
34 addEntryToDictionary(webURL, result)
35 else
36 addEntryToDictionary(webURL, "Error downloading decal")
37 end
38
39 task.wait()
40end
41
42print("Conversion complete")
43
44-- close the dictionary
45outputString = outputString .. "\n}"
46
47-- print the dictionary
48print(outputString)

GetObjectsAllOrNone

Roblox Script Security

Parameters

url: Content

Returns

GetObjectsList

Roblox Script Security

Parameters

urls: Array

Returns

IsLoaded

This function returns true if the client has finished loading the game for the first time.

When all initial Instances in the game have finished replicating to the client, this function will return true.

Unless they are parented to ReplicatedFirst, LocalScripts will not run while the game has not loaded. The following snippet, ran from a LocalScript in ReplicatedFirst will yield until the game has loaded:


1if not game:IsLoaded() then
2 game.Loaded:Wait()
3end
4

See also:


Returns

Whether the client has finished loading the game for the first time.

Code Samples

Custom Loading Screen

1local Players = game:GetService("Players")
2local ReplicatedFirst = game:GetService("ReplicatedFirst")
3
4local player = Players.LocalPlayer
5local playerGui = player:WaitForChild("PlayerGui")
6
7-- Create a basic loading screen
8local screenGui = Instance.new("ScreenGui")
9screenGui.IgnoreGuiInset = true
10
11local textLabel = Instance.new("TextLabel")
12textLabel.Size = UDim2.new(1, 0, 1, 0)
13textLabel.BackgroundColor3 = Color3.fromRGB(0, 20, 40)
14textLabel.Font = Enum.Font.GothamSemibold
15textLabel.TextColor3 = Color3.new(0.8, 0.8, 0.8)
16textLabel.Text = "Loading"
17textLabel.TextSize = 28
18textLabel.Parent = screenGui
19
20-- Parent entire screen GUI to player GUI
21screenGui.Parent = playerGui
22
23-- Remove the default loading screen
24ReplicatedFirst:RemoveDefaultLoadingScreen()
25
26--wait(3) -- Optionally force screen to appear for a minimum number of seconds
27if not game:IsLoaded() then
28 game.Loaded:Wait()
29end
30screenGui:Destroy()

Load

void
Local User Security

Loads a Roblox Place File from a URL.

Parameters

url: Content

The given content URL.


Returns

void

Code Samples

DataModel:Load

1local BASE_URL = "http://www.roblox.com/asset/?id=%d"
2game:Load(BASE_URL:format(1818)) -- Loads Crossroads, an original, *uncopylocked* game by Roblox
3
4-- NOTE: If trying to access a copylocked placed that is not owned by the currently logged in user,
5-- or if used in any code with a security context less than 4, this will not work, and will error.

OpenScreenshotsFolder

void
Roblox Script Security

Returns

void

OpenVideosFolder

void
Roblox Script Security

Returns

void

ReportInGoogleAnalytics

void
Roblox Script Security

Parameters

category: string
action: string
Default Value: "custom"
label: string
Default Value: "none"
value: number
Default Value: "0"

Returns

void

SetFastFlagForTesting

Roblox Script Security

Parameters

name: string
newValue: boolean

Returns

SetFastIntForTesting

Roblox Script Security

Parameters

name: string
newValue: number

Returns

SetFastStringForTesting

Roblox Script Security

Parameters

name: string
newValue: string

Returns

SetPlaceId

void
Plugin Security

This function sets the DataModel.PlaceId of the game instance to the given placeId.

Setting the DataModel.PlaceId is required to access the DataStoreService when the place is unpublished (for example a local .rbxl file). See below for an example. This will only work when the 'Enable Studio Access to API Services` option is enabled under game settings.


1local DataStoreService = game:GetService("DataStoreService")
2
3-- access DataStore 'Data' as place placeId
4game:SetPlaceId(placeId)
5local dataStore = DataStoreService:GetDataStore("Data")
6

You can use DataModel:SetUniverseId() to set the DataModel.GameId of the game instance. However, it is the DataModel.PlaceId that must be set to access the DataStoreService.

Parameters

placeId: number

The ID to set the DataModel.PlaceId to.


Returns

void

SetUniverseId

void
Plugin Security

This function sets the DataModel.GameId of the current game instance to the given universeId. This is useful when testing local .rbxl files that have not been published to Roblox.

If you want to access the DataStoreService in an unpublished place, you should use DataModel:SetPlaceId() instead.

Parameters

universeId: number

The ID to set the DataModel.GameId to.


Returns

void

Shutdown

void
Local User Security

This function shuts down the current game instance.

This function cannot be used by developers to 'shut down' live game servers due to its security context level. Game servers can only be shutdown by the developer from the place's page on the Roblox website.

See also:


Returns

void

GetObjectsAsync

Yields
Roblox Script Security

Parameters

url: Content

Returns

HttpGetAsync

Yields
Roblox Script Security

Parameters

url: string
httpRequestType: HttpRequestType
Default Value: "Default"

Returns

HttpPostAsync

Yields
Roblox Script Security

Parameters

url: string
data: string
contentType: string
Default Value: "*/*"
httpRequestType: HttpRequestType
Default Value: "Default"

Returns

InsertObjectsAndJoinIfLegacyAsync

Yields
Roblox Script Security

Parameters

url: Content

Returns