Global namespace/Basic functions

(Redirected from Type)
< Global namespace

The functions listed below aren't in any specific library, but are global in the script's environment. These are general purpose functions that don't fit into any of the other categories.

assert[edit]

Variant assert(Variant v)



Description:
Throws an error if v is false or nil. Returns the value passed as v if the assert passes.

Example:
assert (false)
Tue Oct 07 10:14:18 2008 - Cmd:1: assertion failed! 
Tue Oct 07 10:14:18 2008 - Cmd, line 1
Tue Oct 07 10:14:18 2008 - stack end
assert (true)
No output

void assert(Variant v, string message)



Description:
Throws an error if 'v' is false or nil, with the error message set as message. Returns the value passed as v if the assert passes.

Example:
assert (false, "This is an error message")
Tue Oct 07 10:15:37 2008 - Cmd:1: This is an error message
Tue Oct 07 10:15:37 2008 - Cmd, line 1
Tue Oct 07 10:15:37 2008 - stack end

collectgarbage[edit]

Variant collectgarbage(string option)

Description:
Performs an operation on the Lua garbage collector based on the specified option. Roblox's Lua sandbox only allows the "count" option to be used, so none of the other standard options are available.

The "count" option returns the total memory in use by Lua (in Kbytes).

Example:
t = {}
for i = 0,20000 do
    table.insert(t,i,i)
end
 
print(collectgarbage("count"))
t = nil
print(collectgarbage("count"))
~535.7998046875
~23.7197265625

dofile[edit]

Variant dofile(string filename)

Description:
(OBSOLETE)

error[edit]

void error(string message)

Description:
Terminates the last protected function called and outputs message as an error message. If the function containing the error is not called in a protected function (pcall), then the script which called the function will terminate. The error function itself never returns and acts like a script error.

void error(string message, int level)

Description:
Terminates the last protected function called and outputs message as an error message.

Usually, error adds some information about the error position at the beginning of the message. The level argument specifies how to get the error position. With level 1 (the default), the error position is where the error function was called. Level 2 points the error to where the function that called error was called; and so on. Passing a level 0 avoids the addition of error position information to the message.

Example:
error ("this is an error message")
Tue Oct 07 08:18:36 2008 - Cmd:1: this is an error message
Tue Oct 07 08:18:36 2008 - Cmd, line 1
Tue Oct 07 08:18:36 2008 - stack end

_G[edit]

array _G

Description:
A table that is shared between all scripts in one instance of Roblox. Scripts can use this to share data, including functions, between them.


Example:
--Script one:
_G.variable = "This a variable in _G."
 
--Script two:
while _G.variable == nil do wait() end --make sure that script one sets the variable before this one tries to read it
print(_G.variable)
"This a variable in _G."


Notes:

  • There are multiple copies of _G in Roblox's Lua implementation, separated by their context level.

gcinfo[edit]

int gcinfo()



Description:
Returns amount of dynamic memory in use.

Example:
print (gcinfo())
a=collectgarbage("count")
print(a)
28 
29.6875


Notes:
  • This is deprecated. Use collectgarbage("count") instead.

getfenv[edit]

void getfenv(Variant<int, function, nil> f)



Description:
Returns the current environment in use by the function. f can be a function or a number that specifies the function at that stack level: Level 1 is the function calling getfenv. If the given function is not a function, or if f is 0, getfenv returns the global environment. The f parameter can be excluded, and it is 1 by default. When using getfenv to get the current environment of a script, it will return the same table every time within the specific thread.

Example:
var1 = 7
var2 = 9
getfenv()["var3"] = 11
for i, v in pairs(getfenv()) do
    print(i, " = ", v)
end
script = Script
var1 = 7
var2 = 9
var3 = 11

getmetatable[edit]

Variant getmetatable(Variant<table, userdata> object)

Description:
Returns the metatable of the specified object if it has one, otherwise returns nil.

If the object does have a metatable, but the metatable has a __metatable field set, the value of __metatable will be returned instead.

Example:
t = {}
print(getmetatable(t))
setmetatable(t,{})
print(getmetatable(t))
nil
table: [hexadecimal memory address]

ipairs[edit]

function, table, int ipairs(table t)

Description:
Returns three values: an iterator function, and the table t.

Example:
This will iterate over the pairs (1,t[1]), (2,t[2]), ···, up to the first integer key absent from the table.

t = {'a', 'b', 'c', nil, 'd'}
for i,v in ipairs(t) do
    print(i, v)
end
1	a
2	b
3	c

load[edit]

Variant<function, nil> load(function func, string chunkName)

Description:
(OBSOLETE)

loadfile[edit]

function loadfile(string path)



Description:
Loads a lua file from the specified path and returns it as a function.

Example:
--File name: file.lua
-- File contents: print("This is the contents of a file.")
 
f = loadfile("C:/file.lua")
f()
This is the contents of a file.


Notes:
  • This is used internally by Roblox, and doesn't really have practical use for developers.

loadstring[edit]

Warning:loadstring cannot be used from a LocalScript, however, it can be used from a Script if loadstring is enabled through the LoadStringEnabled property of ServerScriptService.


Variant<function, Tuple<nil, string>> loadstring(string contents)

Description:
Loads Lua code from a string, and returns it as a function.

Example:
To load and run a given string, use the idiom

assert(loadstring(s))()
a = 2
loadstring("b = 3")()		-- This loads the string to a function, and then calls that function.
print(a+b)
a = 5
b = 1
change = loadstring("b = 2")
print(a+b)
change()
print(a+b)
5
6
7


Notes:
  • Unlike standard Lua 5.1, Roblox's Lua cannot load the binary version of Lua using loadstring.

newproxy[edit]

userdata newproxy()

Description:
Creates a blank userdata with an empty metatable.

local a = newproxy() 
local mt = getmetatable(a) 
print( mt ~= nil )
mt.__index = {Name="Proxy"} 
print( a.Name )
true
Proxy

next[edit]

Variant, Variant next(table t)

Description:
Returns the first key/value pair in the array.

Variant, Variant next(table t, Variant lastKey)



Description:
Returns the next element in the array based on a key that was previously retrieved from a call to next.

Example:
days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
print(next(days))
print(next(days,4))
1 Sunday
5 Thursday -- cf. print(days[4]), which gives you Wednesday


Notes:
  • The order in which the indices are enumerated is not specified, even for numeric indices. To traverse a table in numeric order, use a numerical for or the ipairs function.
  • The behavior of next is undefined if, during the traversal, you assign any value to a non-existent field in the table. You may however modify existing fields. In particular, you may clear existing fields.

os.time[edit]

int os.time()

Description:
Returns how many seconds since the epoch (1 January 1970, 00:00:00), under UTC time.

Notes:

  • This differs from tick(), because tick uses the current system time rather than UTC time.
  • In theory, this value will be the same on all systems, but in practice it will often differ with some seconds.
  • os.time() should be used for cases where you want to get a time difference between two visits - think about giving players a bonus for coming back every day.

int os.time(dictionary dateTable)

Description:
When called with a date table, os.time will return the timestamp which belongs to that date table.

Notes:
This date table can hold the following fields:

Field Valid values Default values or mandatory
year A full year number (ex. 2014) Mandatory
month 1-12 Mandatory
day 1-31 Mandatory
hour 1-31 12
min 0-59 0
sec 0-59 0
isdst True if daylight saving is on false

os.date[edit]

dictionary<Variant<int, bool>> os.date(string formatString, number time)

Description:
Takes a UNIX time stamp and returns information about what date it is. Format string must be either *t or !*t. *t is local time (only useful on the client), and !*t is UTC.

Notes:
The returned dictionary contains the following fields (it is compatible with os.time):

Field Type Description
year int An integer that describes the current year of the Current Era (ex. 2017)
month int An integer between 1 and 12 (starting from January) that describes the current month.
wday int An integer between 1 and 7 (starting from Sunday) that describes the current week day.
yday int An integer between 1 and 366 describing how many days we are into the year.
There can be 366 days if it is a leap year.
day int An integer between 1 and 31 describing the current day of the month.
hour int An integer between 1 and 24 describing the current hour of the day.
min int An integer between 0 and 59 describing the current minute of the hour.
sec int An integer between 0 and 60 describing the current second of the hour.
(60 because the function is described to indicate leap seconds, but in practice it probably doesn't).
isdst bool A boolean describing if daylight savings time is currently active.

os.difftime[edit]

int os.difftime(int t1, int t2)

Description:
Returns the number of seconds from t1 to t2. In Microsoft Windows and systems based on Unix, this is equivalent to t1t2; this is always the case in ROBLOX.

debug.traceback[edit]

string debug.traceback()



Description:
Returns a stack trace of the current thread, which is identical to the one shown in the output when an error occurs.

Example:
print(debug.traceback())
Stack Begin
Script 'print(debug.traceback())', Line 1
Stack End
-- Ran from a Script in workspace called "Script"
local function a()
	print(debug.traceback())
end
function b()
	a()
end
local function c()
	b()
end
c()
Stack Begin
Script 'Workspace.Script', Line 3 - upvalue a
Script 'Workspace.Script', Line 6 - global b
Script 'Workspace.Script', Line 9 - local c
Script 'Workspace.Script', Line 11
Stack End

debug.profilebegin[edit]

Main article: MicroProfiler

void debug.profilebegin(string profileName)



Description:
Marks the starting point of a custom label in the Microprofiler.

Example:
while true do
   debug.profilebegin("custom_label")
   --your code here
   debug.profileend()
   wait()
end

debug.profileend[edit]

void debug.profileend()

Description:
Closes the custom label that was created in this stack's Microprofiler.

pairs[edit]

function, table pairs(table t)

Description:
Returns the next function, and the passed table 't', so that the construction

for k,v in pairs(t) do 
--body
end
will iterate over all key–value pairs of table t.

Example:
t = {1,2,"a","d",c = 12, q = 20}
for i,v in pairs(t) do
	print(i,v)
end
1 1
2 2
3 a
4 d
c 12
q 20


Notes:
  • See the function next for the caveats of modifying the table during its traversal.

pcall[edit]

bool, Variant<string, Tuple<Variant>> pcall(function func, Tuple<Variant> args)



Description:
Calls the function f with the given arguments in protected mode. This means that any error inside f is not propagated; instead, pcall catches the error and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In such case, pcall also returns all results from the call, after this first result. In case of any error, pcall returns false plus the error message.

Example:
function GoodPrint()
    print("Hi Mom!")
end
 
function BadPrint()
    ppppprint("Hi Mom!") -- This will error.
end
 
local success, message = pcall(GoodPrint)
if success then
    -- Stuff
else 
    print("An error occurred: "..message)
end
 
success, message = pcall(BadPrint)
if success then
    -- Stuff
else 
    print("An error occurred: "..message)
end
Hi Mom!
An error occurred: Workspace.Script:6: attempt to call global 'ppppprint' (a nil value)

print[edit]

void print(Tuple<Variant> params)



Description:
Receives any number of arguments, and prints their values to the output, using the tostring function to convert them to strings. print is not intended for formatted output, but only as a quick way to show a value, typically for debugging. For a formatted output, use string.format.

Example:
print("Hello!")
Hello!

rawequal[edit]

bool rawequal(Variant v1, Variant v2)



Description:
Checks whether v1 is equal to v2, without invoking any metamethod.

Example:
print(rawequal (5, 3))
print(rawequal (5, 5))
false
true

rawget[edit]

void rawget(table t, Variant index)



Description:
Gets the real value of table[index], without invoking any metamethod.

Example:
days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
print(rawget (days, 2))
Monday

rawset[edit]

table rawset(table t, Variant index, Variant value)



Description:
Sets the real value of table[index] to value, without invoking any metamethod. table must be a table, index any value different from nil, and value any value.

Example:
rawset (_G, "test", 42) 
print (_G.test)
42

select[edit]

Tuple<Variant> select(int index, Tuple<Variant> args)



Description:
Returns all arguments after argument number index.

Example:
print(select(3, "a", "b", "c", "d", "e", 1, 2, 3))
c d e 1 2 3

int select(string cmd = "#", Tuple<Variant> args)

Description:
Returns the total number of arguments that were passed after the cmd argument.

The cmd argument must be "#" to use select in this fashion.

Example:
print(select("#", "a", "b", "c", "d", "e", 1, 2, 3))
8

setfenv[edit]

Variant<function, nil> setfenv(Variant<function, int> f, table fenv)

Description:
Sets the environment to be used by the given function. f can be a function or a number that specifies the function at that stack level: Level 1 is the function calling setfenv. setfenv returns the given function.

As a special case, when f is 0 setfenv changes the environment of the running thread. In this case, setfenv returns no values.

Example:
_G.a = 1   -- create a global variable
setfenv(1, {_G = _G}) -- change current environment
_G.print(a)
_G.print(_G.a)
nil
1


Notes:

setmetatable[edit]

table setmetatable(table t, Variant<table, nil> setTo)



Description:
Sets the metatable for the given table. If setTo is nil, the metatable of the given table is removed. If the original metatable has a "__metatable" field, this will raise an error. This function returns the table t, which was passed to the function.

Example:
local t = {"a","b","c"}
 
local mt = {
	__pow = function(tbl, num)
		return 3 ^ num
	end
}
 
setmetatable(t,mt)
 
for i, value in pairs(t) do
	print(i, "=", value)
end
 
print("t ^ 2 = "..t ^ 2)
1 = a
2 = b
3 = c
t ^ 2 = 9

tonumber[edit]

Variant<number, nil> tonumber(Variant arg)

Description:
Attempts to convert the arg into a number in base-10. If it cannot be converted, this function returns nil.

void tonumber(Variant arg, int base)



Description:
Attempts to convert the arg into a number with a specified base to interpret the value in. The base may be any integer between 2 and 36, inclusive. In bases above 10, the letter 'A' (in either upper or lower case) represents 10, 'B' represents 11, and so forth, with 'Z' representing 35. In base 10 (the default), the number may have a decimal part, as well as an optional exponent part. In other bases, only unsigned integers are accepted.

Example:
print(tonumber(255))
print(tonumber (11111111, 2))
print(tonumber ("FF", 16))
255
255
255

tostring[edit]

string tostring(Variant e)



Description:
Receives an argument of any type and converts it to a string in a reasonable format.

Example:
a=tostring(2+2)
print("The answer to 2+2 is " .. a)
The answer to 2+2 is 4


Notes:
  • If the metatable of e has a "__tostring" field, then tostring calls the corresponding value with e as argument, and uses the result of the call as its result.
  • For complete control of how number are converted, use string.format.

type[edit]

string type(Variant v)



Description:
Returns the type of its only argument, coded as a string. The possible results of this function are "nil" (a string, not the value nil), "number", "string", "boolean", "table", "function", "thread", and "userdata".

Example:
print(type (true))
print(type (3))
boolean
number

unpack[edit]

void unpack(table list, int i = 1, int j = #list)

Description:
Returns the elements from the given table. This function is equivalent to

return list[i], list[i+1], ···, list[j]
except that the above code can be written only for a fixed number of elements. By default, i is 1 and j is the length of the list, as defined by the length operator.

Example:
t = { "the", "quick", "brown" }
print (unpack (t))
the quick brown

_VERSION[edit]

string _VERSION

Description:
A global variable (not a function) that holds a string containing the current interpreter version. The current contents of this variable is "Lua 5.1".


Example:
print(_VERSION)
Lua 5.1


Notes:

  • This value is misleading, as Roblox actually uses a modded version of Lua 5.1.4

xpcall[edit]

bool, Variant<string, Variant> xpcall(function f, function err)

Description:
This function is similar to pcall, except that you can set a new error handler.

xpcall calls function f in protected mode, using err as the error handler. Any error inside f is not propagated; instead, xpcall catches the error, calls the err function with the original error object, and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In this case, xpcall also returns all results from the call, after this first result. In case of any error, xpcall returns false plus the result from err.

Example:
function handle(err)
    return "ERROR: " .. err:gsub("(.-:)","")
end
 
function f()
    local a = nil
    return a+1
end
 
print(xpcall(f,handle))
false ERROR: attempt to perform arithmetic on local 'a' (a nil value)