Common Functions

Common functions are shared and available to use within both server and client script files.

Did you know there are useful static variables set up on the main TMC object for you to use! See below.

VariableTypeDescription

TMC.IsDev

Bool

Used to determine if the server is running in development mode

TMC.GameType

String

Stores the current game type. I.e. gta5 or rdr3

TMC.IsGTA5

Bool

Is the game type gta5

TMC.IsRDR3

Bool

Is the game type rdr3

String

RandomStr

Returns a random string at the specified length using uppercase and lowercase letters

ParameterRequiredTypeDescription

length

Number

The length of the string to generate

Lua
local randomStr = TMC.Common.RandomStr(100)
Javascript
let randomStr = TMC.Common.RandomStr(100);

RandomInt

Returns a random string at the specified length using numeric characters

ParameterRequiredTypeDescription

length

Number

The length of the string to generate

Lua
local randomInt = TMC.Common.RandomInt(10)
-- Example output: 9274735819
Javascript
let randomInt = TMC.Common.RandomInt(10);
// Example output: 01864963759

SplitStr

Returns an array of strings

ParameterRequiredTypeDescription

str

String

The string that needs to be split

delimiter

String

A string defining the delimiter to use

Lua
local fields = TMC.Common.SplitStr('this|is|a|test', '|')
-- { 'this', 'is', 'a', 'test' }
Javascript
let fields = TMC.Common.SplitStr('this|is|a|test', '|');
// [ 'this', 'is', 'a', 'test' ]

GenerateVIN

Returns a string

ParameterRequiredTypeDescription

local

Bool

If the car is a local or a player owned vehicle. Determines a small identifier within the VIN.

Lua
local spawnedVehVIN = TMC.Common.GenerateVIN(true)
local vehicleShopPurchase = TMC.Common.GenerateVIN()
Javascript
let spawnedVehVIN = TMC.Common.GenerateVIN(true)
let vehicleShopPurchase = TMC.Common.GenerateVIN()

GenerateBankAccount

Returns a formatted bank account number

Lua
local newAccNumber = TMC.Common.GenerateBankAccount()
Javascript
let newAccNumber = TMC.Common.GenerateBankAccount();

TrimPlate

Returns a string containing the plate passed in without any spaces

ParameterRequiredTypeDescription

plate

String

The plate to trim

Lua
local trimmedPlate = TMC.Common.TrimPlate('  1234  ')
Javascript
let trimmedPlate = TMC.Common.TrimPlate('  1234  ');

Math

Clamp

Returns a value within a range of values between a defined minimum bound and a maximum bound.

ParameterRequiredTypeDescription

value

Number

The value to clamp

min

Number

The minimum bound

max

Number

The maximum bound

Lua
local valToClamp = math.random(100)
local val = TMC.Common.Clamp(valToClamp, 20, 80)
local valMax = TMC.Common.Clamp(valToClamp, nil, 80)
Javascript
let valToClamp = Math.random() * 100;
let val = TMC.Common.Clamp(valToClamp, 20, 80);
let valMax = TMC.Common.Clamp(valToClamp, undefined, 80);

MathAverage

Returns the average for numbers passed in

ParameterRequiredTypeDescription

data

Number Array

An array of numbers to calcualte the average of.

Lua
local avg = TMC.Common.MathAverage({ 10, 20, 15, 50, 35 })
Javascript
let avg = TMC.Common.MathAverage([ 10, 20, 15, 50, 35 ]);

TrueRandom

Returns a better random number

ParameterRequiredTypeDescription

min

Number

A min value

max

Number

A max value

Lua
local rand = TMC.Common.TrueRandom(1, 1000)
Javascript
let rand = TMC.Common.TrueRandom(1, 1000);

RandomChance

Returns a bool indicating if the chance succeeded

ParamaeterRequiredTypeDescription

min

Number

A min value

max

Number

A max value

chance

Number

The amount of chance

Lua
if TMC.Common.RandomChance(1, 100, 20) then
    -- reward
end
Javascript
if (TMC.Common.RandomChance(1, 100, 20) {
    // reward
}

MathRound

Rounds a number

ParameterRequiredTypeDescription

value

Number

The number you would like to round

numDecimalPlaces

Number

The amount of decimal places you would like to include, this defaults to 0

Lua
local roundedNumber = TMC.Common.MathRound(10.5)
Javascript
let roundedNumber = TMC.Common.MathRound(10.5)

MathGroupDigits

Groups a number together into a human-readable format. For example, convert 10000 to 10,000

ParameterRequiredTypeDescription

value

Number

The number you'd like to convert

Lua
local groupedNumber = TMC.Common.MathGroupDigits(10000)
Javascript
let groupedNumber = TMC.Common.MathGroupDigits(10000)

MathTrim

Removes all whitespace around a number in a string

ParameterRequiredTypeDescription

value

String

String to clear whitespace from

Lua
local trimmedNumber = TMC.Common.MathTrim(" 5000 ")
Javascript
let trimmedNumber = TMC.Common.MathTrim(" 5000 ")

Other

GetTime

Returns a moment formatted date string or epoch timestamp (in milliseconds).

ParameterRequiredTypeDescription

timestamp

Number/String

An optional epoch timestamp or date string that should be used instead of current time. If not provided will default to the current time.

format

String

Moment date formatting to use. Defaults to return the epoch timestamp.

Lua
local currentTime = TMC.Common.GetTime()
local currentTimeFormatted = TMC.Common.GetTime(nil, 'YYYY/MM/DD')
Javascript
let currentTime = TMC.Common.GetTime()
let currentTimeFormatted = TMC.Common.GetTime(undefined, 'YYYY/MM/DD');

Decode

ParameterRequiredTypeDescription

val

Any

Will decode json if valid json is passed. Useful when you don't trust the data source.

Lua
-- Both will have the same result
local obj = TMC.Common.Decode('{ "test": true }')
local obj2 = TMC.Common.Decode({ test = true })
Javascript
// Both will have the same result
let obj = TMC.Common.Decode('{ "test": true }');
let obj2 = TMC.Common.Decode({ test: true });

Dump

Returns a nicely formatted string based on value passed in. Similar to json.encode. Will also automatically output to console. Mainly used for debugging purposes.

ParameterRequiredTypeDescription

val

Any

The value to convert

Lua
TMC.Common.Dump({ test = true })
-- Outputs: { [test] = true }
Javascript
TMC.Common.Dump({ test: true });
// Outputs: { [test] = true }

TablePrint

Has no return value. Prints object to console in a table format. Mainly used for debugging purposes.

ParameterRequiredTypeDescription

val

Any

The value to print to console

Lua
TMC.Common.TablePrint({ test = true, test2 = { innerTest = false } })
-- Outputs to console:
--[[
Table:
    test = true
    test2:
        innerTest = false
]]
Javascript
TMC.Common.Dump({ test: true, test2: { innerTest: false } });
// Outputs to console:
///Table:
///    test = true
///    test2:
///        innerTest = false

Shuffle

Returns the shuffled array

ParameterRequiredTypeDescription

tab

Array

The array to shuffle

Lua
TMC.Common.Shuffle({ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 })
Javascript
TMC.Common.Shuffle([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]);

Merge

Returns a combined object. Will overwrite object 1's value if the same key exists. Works recursively.

ParameterRequiredTypeDescription

obj1

Object

First object

obj2

Object

Second object to merge over the top of object 1

Lua
local res = TMC.Common.Merge({ one = 1, two = 2, test = 3 }, { three = 3, test = 4 })
-- Result: { one = 1, two = 2, three = 3, test = 4 }
Javascript
let res = TMC.Common.Merge({ one: 1, two: 2, test: 3 }, { three: 3, test: 4 });
// Result: { one: 1, two: 2, three: 3, test: 4 }

Combine

Returns an array combined from the parameters

ParameterRequiredTypeDescription

arr1

Array

First array to combine

arr2

Array

Second array to combine

Lua
local newArr = TMC.Common.Combine({ 1, 2, 3 }, { 4, 5, 6, 1 })
-- Result: { 1, 2, 3, 4, 5, 6, 1 }
Javascript
let newArr = TMC.Common.Combine([ 1, 2, 3 ], [ 4, 5, 6, 1 ]);
// Result: [ 1, 2, 3, 4, 5, 6, 1 ]

CopyTable

Returns an object with the same data as the parameter passed in

ParameterRequiredTypeDescription

obj

Object

Object to make a copy of

Lua
local res = TMC.Common.CopyTable({ one = 1, two = 2, test = 3 })
-- Result: { one = 1, two = 2, three = 3 }
Javascript
let res = TMC.Common.CopyTable({ one: 1, two: 2, test: 3 });
// Result: { one: 1, two: 2, three: 3 }

TableHas

Returns a bool checking if the array contains a specific value

ParameterRequiredTypeDescription

arr

Array

The array to search

val

Any

The value to search for within the array

Lua
if TMC.Common.TableHas({ 1, 5, 10 }, 10) then
end
Javascript
if (TMC.Common.TableHas([ 1, 5, 10 ], 10) {}

GetGridZoneAtCoords

Returns a number based on the coords passed in. This would be used as a way to divide the map up into a grid.

ParameterRequiredTypeDescription

coords

Vector3

The position on the map to get the grid number for

Lua
local zoneId = TMC.Common.GetGridZoneAtCoords(vector3(100.0, 100.0, 50.0))
Javascript
let zoneId = TMC.Common.GetGridZoneAtCoords(Vector3(100.0, 100.0, 50.0));

GetPermissionRank

Returns the permission rank id from the name.

If the rank can't be found, it defaults to 1

ParameterRequiredTypeDescription

permission

String

Name of the permission rank

Lua
local rankId = TMC.Common.GetPermissionRank("helper")
Javascript
let rankId = TMC.Common.GetPermissionRank("helper")

IsDepRunning

Checks if a resource is currently running

ParameterRequiredTypeDescription

resName

String

Name of the resource

Lua
if not TMC.Common.IsDepRunning("dispatch") then
    print("Dispatch isn't running!")
end
Javascript
if(!TMC.Common.IsDepRunning("dispatch")) {
    console.log("Dispatch isn't running!")
}

TableSortAlphabetical

Sorts a table alphabetically based on the keys

ParameterRequiredTypeDescription

data

Array

Table of data to sort

Lua
local table = {
    ["Josh"] = 5,
    ["Chris"] = 20,
    ["Alex"] = 1,
    ["Richard"] = 50
}

local sortedTable = TMC.Common.TableSortAlphabetical(table)
Javascript
let table = {
    "Josh": 5,
    "Chris": 20,
    "Alex": 1,
    "Richard": 50
}

let sortedTable = TMC.Common.TableSortAlphabetical(table)

Jobs

GetJob

Returns a job object

ParameterRequiredTypeDescription

job

String

The key for the job you want to find

local job = TMC.Common.GetJob('police')
Javascript
let job = TMC.Common.GetJob('police');

GetJobGrade

Returns a single grade from the job object

ParameterRequiredTypeDescription

job

String

The key for the job you want to find

grade

Number

The number of the grade you want to find

Lua
local jobGrade = TMC.Functions.GetJobGrade('police', 2)c
Javascript
let jobGrade = TMC.Functions.GetJobGrade('police', 2);

JobLabel

Returns the job label as a string

ParameterRequiredTypeDescription

job

String

The key for the job

Lua
local jobLabel = TMC.Common.JobLabel('police')
Javascript
let jobLabel = TMC.Common.JobLabel('police');

OnlinePlayersWithJob

Returns a number

ParameterRequiredTypeDescription

job

String

The job key

onDuty

Bool

Must be true, offDuty player checks are not supported at this time

grade

Number

If provided will check for players with at least the grade specified

Lua
if TMC.Common.OnlinePlayersWithJob('police', true, 3) > 0 or TMC.Common.OnlinePlayersWithJob('sheriff', true) > 0 then
    print('At least 1 sheriff or grade 3 and above police is on duty')
end
Javascript
if (TMC.Common.OnlinePlayersWithJob('police', true, 3) > 0 || TMC.Common.OnlinePlayersWithJob('sheriff', true) > 0) {
    console.log('At least 1 sheriff or grade 3 and above police is on duty');
}

Inventory

GenerateInventory

Returns an array of pre-populated item slots in the correct format.

ParameterRequiredTypeDescription

slots

Number

The number of slots to generate in the inventory

Lua
local inv = TMC.Common.GenerateInventory(40)
Javascript
let inv = TMC.Common.GenerateInventory(40);

GetItemQuality

Returns a number for the quality of an item calculated based on the decay.

ParameterRequiredTypeDescription

itemInfo

Object

The info object of a stackable or unique inventory item

Lua
local quality = TMC.Common.GetItemQuality(item.info)
Javascript
let quality = TMC.Common.GetItemQuality(item.info);

EnforceItemDecay

Forcibly updates an item decay information and returns array

ParameterRequiredTypeDescription

itemInfo

Object

The info object an item

info

Object

The information to update from

Lua
local updateInformation = TMC.Common.EnforceItemDecay(newDecay, item.info)
Javascript
let updateInformation = TMC.Common.EnforceItemDecay(newDecay, item.info)

UnfreezeItem

Forcibly updates an item and removes feezer data

ParameterRequiredTypeDescription

info

Object

The information to update from

Lua
local updateInformation = TMC.Common.UnfreezeItem(item.info)
Javascript
let updateInformation = TMC.Common.UnfreezeItem(item.info)

GetItemExpiry

Returns the time till decays for an item. Either returns false or item in seconds

ParameterRequiredTypeDescription

info

Object

The information to read from

Lua
local expiry = TMC.Common.GetItemExpiry(item.info)
Javascript
let expiry = TMC.Common.GetItemExpiry(item.info)

TableCoordsToVec

Converts a table of coords to a vector

ParameterRequiredTypeDescription

tab

Object

Table of coords

Lua
local coords = [
    x = 10,
    y = 10,
    z = 10,
    w = 10
]

local convertedCoords = TMC.Common.TableCoordsToVec(coords)
Javascript
let coords = {
    x: 10,
    y: 10,
    z: 10,
    w: 10
}

let convertedCoords = TMC.Common.TableCoordsToVec(coords)

Status Effects

These functions will not affect the value if you are not running the Status Effect resource.

TryApplyLuck

Based on the player's current luck adjust the value accordingly

ParameterRequiredTypeDescription

value

Number

The number to minipulate

negativeCheck

Bool

Decrease the value if luck check passes

src

Number

Source of the player (Required if called from server)

Lua
local value = TMC.Common.TryApplyLuck(20)
Javascript
let value = TMC.Common.TryApplyLuck(20)

RandomChanceWithLuck

Alike TMC.Common.RandomChance however with weighting based on current luck

ParameterRequiredTypeDescription

min

Number

Minimum number possible

max

Number

Maximum number possible

chance

Number

Amoiunt of chance

negativeCheck

Bool

Decrease the value if luck check passes

maxPercentage

Number

Maximum percentage chance possible (Defaults to 0.3)

src

Number

Source of the player (Required if called from server)

Lua
local value = TMC.Common.RandomChanceWithLuck(20, true, 0.5)
Javascript
let value = TMC.Common.RandomChanceWithLuck(20, true, 0.5)

Last updated