nss_libs - Shared Helper
The methods of the shared helper are available for and inherited to both client and server side.
In the following you will find the methods of the shared helper used for example on the server side via imported SERVER_HELPER variable.
IMPORTANT: DO NOT USE THESE NssLibsSharedHelper DIRECTLY, USE FOR CLIENT NssLibsClientHelper AND FOR SERVER NssLibsServerHelper!
Methods
.copyThisTo(table, unique_id_prefix?)
Note
This method is used to copy the methods of the shared helper to another table (e.g. a class like client helper or server helper).
| Param | Type | Default | Description |
|---|---|---|---|
table | table | — | The table to copy the methods of the shared helper to |
unique_id_prefix | string? | — | The unique id prefix to use for the table |
Returns nothing.
local my_table = {}
SERVER_HELPER:copyThisTo(my_table, 'my_table')
local uid = my_table:getUniqueId()
print(uid).getHashKey(name_or_hash)
| Param | Type | Default | Description |
|---|---|---|---|
name_or_hash | string | number | — | The name to get the hash key from. If a hash is given it will be returned as is |
Returns number — the hash key.
local hash = SERVER_HELPER:getHashKey('prop_beach_lotion_01')
print(hash).hasTableEntries(obj)
| Param | Type | Default | Description |
|---|---|---|---|
obj | table | any | — | The value to check if it is a table and has entries |
Returns boolean — true if the value is a table and has entries. Otherwise false.
local has_entries = SERVER_HELPER:hasTableEntries({ 1, 2, 3 })
print(has_entries) -- truelocal has_entries = SERVER_HELPER:hasTableEntries({})
print(has_entries) -- falselocal has_entries = SERVER_HELPER:hasTableEntries('Hello')
print(has_entries) -- falselocal has_entries = SERVER_HELPER:hasTableEntries({ a = 1, b = 2, c = 3 })
print(has_entries) -- truelocal has_entries = SERVER_HELPER:hasTableEntries(nil)
print(has_entries) -- false.toFloat(value)
| Param | Type | Default | Description |
|---|---|---|---|
value | number | — | The value to convert to float |
Returns number — the floated value.
local float = SERVER_HELPER:toFloat(1)
print(float) -- 1.0.toInt(value)
| Param | Type | Default | Description |
|---|---|---|---|
value | number | — | The value to convert to integer |
Returns number — the integer value.
local int = SERVER_HELPER:toInt(1.7)
print(int) -- 1.round(num, decimals)
| Param | Type | Default | Description |
|---|---|---|---|
num | number | — | The number to round |
decimals | number | — | The number of decimals to round |
Returns number — the rounded number.
local rounded = SERVER_HELPER:round(1.2345, 2)
print(rounded) -- 1.23.getDecimalCount(num)
| Param | Type | Default | Description |
|---|---|---|---|
num | number | — | The number to get the decimal count from |
Returns number — the decimal count.
local decimal_count = SERVER_HELPER:getDecimalCount(1.2345)
print(decimal_count) -- 4.inlineError(message, traceback?)
| Param | Type | Default | Description |
|---|---|---|---|
message | string | — | The error message |
traceback | string? | — | The traceback string |
Returns nothing.
SERVER_HELPER:inlineError('This is an error message')SERVER_HELPER:inlineError('This is an error message', 'Line 12 in file server.lua').inlineWarning(message, traceback?)
| Param | Type | Default | Description |
|---|---|---|---|
message | string | — | The warning message |
traceback | string? | — | The traceback string |
Returns nothing.
SERVER_HELPER:inlineWarning('This is a warning message')SERVER_HELPER:inlineWarning('This is a warning message', 'Line 12 in file server.lua').getEmptyFunction()
This method is useful if you have to use an empty function as a default value.
Returns function — an empty function.
local empty_function = SERVER_HELPER:getEmptyFunction()
empty_function() -- Does nothing.strTrim(str)
| Param | Type | Default | Description |
|---|---|---|---|
str | string | number | — | The string to trim |
Returns string — the trimmed string.
local trimmed = SERVER_HELPER:strTrim(' Hello ')
print(trimmed) -- 'Hello'.strSplit(str, separator?, max_times?)
| Param | Type | Default | Description |
|---|---|---|---|
str | string | — | The string to split |
separator | string? | " " | The separator to split the string |
max_times | number? | -1 | The maximum times to split the string. -1 for infinite |
Returns table<string> — a table with the split strings.
local parts = SERVER_HELPER:strSplit('Hello,World', ',')
print(json.encode(parts)) -- {'Hello', 'World'}local parts = SERVER_HELPER:strSplit('Hello,World', ',', 1)
print(json.encode(parts)) -- {'Hello'}.isSteamWebApiKeyAvailable()
Checks the convar steam_webApiKey if it is available. See convar documentation for more information.
Returns boolean — true if the Steam Web API key is available. Otherwise false.
local is_available = SERVER_HELPER:isSteamWebApiKeyAvailable()
print(is_available).getKeysFromTable(tbl)
| Param | Type | Default | Description |
|---|---|---|---|
tbl | table | — | The table to get the keys from |
Returns table<string|number> — a table with the keys of the given table.
local keys = SERVER_HELPER:getKeysFromTable({ a = 1, b = 2, c = 3 })
print(json.encode(keys)) -- {'a', 'b', 'c'}.cleanFunctions(obj)
In case you want use json.encode on an object that contains functions you can use this method to clean the functions.
| Param | Type | Default | Description |
|---|---|---|---|
obj | any | — | The object to clean the functions from |
Returns the cleaned object.
local obj = {
a = 1,
b = function()
-- Some things...
end,
c = 3
}
local cleaned = SERVER_HELPER:cleanFunctions(obj)
print(json.encode(cleaned)) -- {a:1, c:3}.getDayMonthYearFromString(str, format?)
| Param | Type | Default | Description |
|---|---|---|---|
str | string | — | The date string |
format | string? | Config.DefaultDateFormat | The format of the date string. Placeholders: D (day), M (month), Y (year) |
Returns NssLibsSharedHelperDateObject — the date object.
local date = SERVER_HELPER:getDayMonthYearFromString('01.02.2021', 'D.M.Y')
print(date.day, date.month, date.year) -- 1, 2, 2021.escapeMagicChars(str)
Escape the magic characters from a string which should be used as find pattern in string:gsub.
| Param | Type | Default | Description |
|---|---|---|---|
str | string | — | The string to escape the magic characters from |
Returns string — the escaped string.
local search_pattern = SERVER_HELPER:escapeMagicChars('%Hello 42 Worlds%')
local escaped_find_pattern = SERVER_HELPER:escapeMagicChars('%Hello')
print(escaped_find_pattern) -- '%%Hello'
local result = search_pattern:gsub(escaped_find_pattern, "%Bye")
print(result) -- '%Bye 42 Worlds%'.debouncedClock(delay_in_ms, cb)
In contrast to debounced(), the cb is called at least every delay_in_ms value if the function is called continuously at shorter intervals than the delay_in_ms value. The delay is therefore not reset with every call.
| Param | Type | Default | Description |
|---|---|---|---|
delay_in_ms | number | — | The delay in milliseconds |
cb | function | — | The callback function |
Returns function — the debounced function.
local debounced = SERVER_HELPER:debouncedClock(1000, function()
print('Debounced function called')
end)
debounced()
Citizen.Wait(1500)
-- Output: Debounced function called after 1000ms. Because 1000ms is the maximum delay.local debounced = SERVER_HELPER:debouncedClock(1000, function()
print('Debounced function called')
end)
-- Call the debounced function continuously.
Citizen.CreateThread(function()
while true do
debounced()
Citizen.Wait(750)
end
end)
-- Output: Each 1000ms the debounced function will be called. Because 1000ms is the maximum delay..debounced(delay_in_ms, cb)
This is useful if you want to debounce a function. E.g. if you want to call a function only once after multiple calls in a short time.
| Param | Type | Default | Description |
|---|---|---|---|
delay_in_ms | number | — | The delay in milliseconds |
cb | function | — | The callback function |
Returns function — the debounced function.
local debounced = SERVER_HELPER:debounced(1000, function()
print('Debounced function called')
end)
debounced()
Citizen.Wait(1500)
-- Output: Debounced function called after 1000ms. Because 1000ms is the maximum delay.local debounced = SERVER_HELPER:debounced(1000, function()
print('Debounced function called')
end)
-- Call the debounced function continuously.
Citizen.CreateThread(function()
while true do
debounced()
Citizen.Wait(750)
end
end)
-- Output: There is no output until the while loop ends because every time the debounced function is called the delay
-- is reset..isFloat(value)
| Param | Type | Default | Description |
|---|---|---|---|
value | any | — | The value to check if it is a float |
Returns boolean — true if the value is a float. Otherwise false.
local is_float = SERVER_HELPER:isFloat(1.7)
print(is_float) -- truelocal is_float = SERVER_HELPER:isFloat(1)
print(is_float) -- falselocal is_float = SERVER_HELPER:isFloat('Hello')
print(is_float) -- false.isFunction(value)
| Param | Type | Default | Description |
|---|---|---|---|
value | any | — | The value to check if it is a function |
Returns boolean — true if the value is a function. Otherwise false.
local is_function = SERVER_HELPER:isFunction(function()
end)
print(is_function) -- truelocal is_function = SERVER_HELPER:isFunction(1)
print(is_function) -- falselocal is_function = SERVER_HELPER:isFunction('Hello')
print(is_function) -- false.isTable(value)
| Param | Type | Default | Description |
|---|---|---|---|
value | any | — | The value to check if it is a table |
Returns boolean — true if the value is a table. Otherwise false.
local is_table = SERVER_HELPER:isTable({ a = 1, b = 2, c = 3 })
print(is_table) -- truelocal is_table = SERVER_HELPER:isTable({ 1, 2, 3 })
print(is_table) -- truelocal is_table = SERVER_HELPER:isTable(1)
print(is_table) -- falselocal is_table = SERVER_HELPER:isTable('Hello')
print(is_table) -- false.isTableArray(value, prevent_cache?)
This method uses a cache to prevent multiple checks of the same table with high cost of performance.
| Param | Type | Default | Description |
|---|---|---|---|
value | any | — | The value to check if it is a table array |
prevent_cache | boolean? | — | If true the cache will be prevented |
Returns boolean — true if the value is a table array. Otherwise false.
local is_table_array = SERVER_HELPER:isTableArray({ 1, 2, 3 })
print(is_table_array) -- truelocal is_table_array = SERVER_HELPER:isTableArray({ a = 1, b = 2, c = 3 })
print(is_table_array) -- falselocal is_table_array = SERVER_HELPER:isTableArray(1)
print(is_table_array) -- falselocal is_table_array = SERVER_HELPER:isTableArray('Hello')
print(is_table_array) -- false.createThreadSafeMonitor(interval_in_ms, cb_function)
Creates a new thread with a while loop that is thread safe. It can be started multiple times - but it will be started only once if it was already started. This is important if different sources triggers the monitor to start or stop.
| Param | Type | Default | Description |
|---|---|---|---|
interval_in_ms | number | — | The interval of the loop in milliseconds |
cb_function | function | — | The callback function. See NssLibsSharedHelperMonitorCallback |
Returns NssLibsSharedHelperMonitor — the monitor instance.
-- Example for simple monitor which is called every 1000ms.
local monitor = SERVER_HELPER:createThreadSafeMonitor(1000, function()
print('Monitor called')
end)
monitor:start()
-- Output: Monitor called every 1000ms..unixTimestampToDate(unix_timestamp)
| Param | Type | Default | Description |
|---|---|---|---|
unix_timestamp | number | — | The unix timestamp to convert to date |
Returns number, number, number, number, number, number — the date as year, month, day, hour, minute, second.
local year, month, day, hour, minute, second = SERVER_HELPER:unixTimestampToDate(1612137600)
print(year, month, day, hour, minute, second) -- 2021, 2, 1, 0, 0, 0.dateToUnixTimestamp(year, month, day, hour, minute, second)
| Param | Type | Default | Description |
|---|---|---|---|
year | number | — | The year |
month | number | — | The month |
day | number | — | The day |
hour | number | — | The hour |
minute | number | — | The minute |
second | number | — | The second |
Returns number — the unix timestamp.
local timestamp = SERVER_HELPER:dateToUnixTimestamp(2021, 2, 1, 0, 0, 0)
print(timestamp) -- 1612137600.padWithZeros(number, length)
| Param | Type | Default | Description |
|---|---|---|---|
number | number | — | The number to pad with zeros |
length | number | — | The length of the number |
Returns string — the padded number.
local padded = SERVER_HELPER:padWithZeros(42, 5)
print(padded) -- '00042'.createResourceEventName(resource_name, event_name)
This is useful if you have to create event names dynamically in the same way as the server and client does.
This method is for internal use primary.
| Param | Type | Default | Description |
|---|---|---|---|
resource_name | string | — | The resource name |
event_name | string | — | The event name |
Returns string — the resource event name.
local resource_name = GetCurrentResourceName() -- e.g. 'my_resource'
local resource_event_name = SERVER_HELPER:createResourceEventName(resource_name, 'my_event')
print(resource_event_name) -- 'my_resource:my_event'
TriggerClientEvent(resource_event_name, -1, 'Hello')local resource_name = GetCurrentResourceName() -- e.g. 'my_resource'
local resource_event_name = CLIENT_HELPER:createResourceEventName(resource_name, 'my_event')
print(resource_event_name) -- 'my_resource:my_event'
RegisterServerEvent(resource_event_name)
AddEventHandler(resource_event_name, function(message)
print(message) -- 'Hello'
end).isTableEqual(table1, table2, deep?)
| Param | Type | Default | Description |
|---|---|---|---|
table1 | table | — | The first table to compare |
table2 | table | — | The second table to compare |
deep | boolean? | false | If true the nested tables will be compared too |
Returns boolean — true if the tables are equal. Otherwise false.
local is_equal = SERVER_HELPER:isTableEqual({ a = 1, b = 2, c = 3 }, { a = 1, b = 2, c = 3 })
print(is_equal) -- truelocal is_equal = SERVER_HELPER:isTableEqual({ a = 1, b = 2, c = 3 }, { a = 1, b = 2, c = 4 })
print(is_equal) -- falselocal is_equal = SERVER_HELPER:isTableEqual({ a = 1, b = 2, c = 3 }, { a = 1, b = 2 })
print(is_equal) -- falselocal is_equal = SERVER_HELPER:isTableEqual({ a = 1, b = { x = 1 }, c = 3 }, { a = 1, b = { x = 1 }, c = 3 })
print(is_equal) -- true.createCallbackApi(callback, resource_name)
Creates a simple callback handler.
If the resource of the given resource_name is stopped the callback will be disabled/destroyed automatically.
| Param | Type | Default | Description |
|---|---|---|---|
callback | function | — | The callback which will be handled by the callback api |
resource_name | string | — | The owning resource of the callback |
Returns NssLibsSharedHelperCallbackHandlerCbApi — the callback api instance.
local callback = function(a, b, c)
print(a, b, c)
end
---@type NssLibsSharedHelperCallbackHandlerCbApi
local callback_api = SERVER_HELPER:createCallbackApi(callback, GetCurrentResourceName())
callback_api:call(1, 2, 3)
-- Output: 1, 2, 3
callback_api:disable()
callback_api:call(1, 2, 3)
-- Output nothing because the callback is disabledObjects
NssLibsSharedHelperDateObject
| Field | Type | Description |
|---|---|---|
day | number | The day of the date |
month | number | The month of the date |
year | number | The year of the date |
NssLibsSharedHelperMonitorCallback
Has no parameters and no return value.
NssLibsSharedHelperMonitor
Api for the monitor.
.isRunning()
Returns boolean — true if the monitor is running. Otherwise false.
.start()
Starts the monitor (if not already started).
Returns NssLibsSharedHelperMonitor — the monitor instance.
.stop()
Stops the monitor (if not already stopped).
Returns NssLibsSharedHelperMonitor — the monitor instance.
NssLibsSharedHelperEventHandlerApi
The following methods uses the following base structure for the examples:
local event_name = 'your_event_name'
local resource_name = GetCurrentResourceName()
local callback = function(...)
print('Event ' .. tostring(event_name) .. ' for ' .. tostring(resource_name) .. 'is triggered:', ...)
end
local event_handler_api = SERVER_HELPER:addEventHandler(event_name, callback, resource_name).getResourceName()
New since version 0.35.0
Returns string — the resource name of the event handler api.
print(event_handler_api:getResourceName())
-- Output: 'resource_name_of_the_owning_resource'.setCustomData(key, value)
New since version 0.35.0
| Param | Type | Default | Description |
|---|---|---|---|
key | string | number | — | The key to set |
value | any | — | The value to set |
Returns NssLibsSharedHelperEventHandlerApi — the event handler instance.
event_handler_api:setCustomData('my_key', 'my_value')
print(event_handler_api:getCustomData('my_key'))
-- Output: 'my_value'.getCustomData(key)
New since version 0.35.0
| Param | Type | Default | Description |
|---|---|---|---|
key | string | number | — | The key to get |
Returns any — the value of the custom data.
event_handler_api:setCustomData('my_key', 'my_value')
print(event_handler_api:getCustomData('my_key'))
-- Output: 'my_value'.addSourceToCallback()
New since version 0.35.0
For server side only. Adds the source as first argument to the callback.
Returns NssLibsSharedHelperEventHandlerApi — the event handler instance.
local event_name = 'your_event_name'
local resource_name = GetCurrentResourceName()
local callback = function(source, ...)
print('Source:', source, 'Event ' .. tostring(event_name) .. ' for ' .. tostring(resource_name) .. 'is triggered:', ...)
end
local event_handler_api = SERVER_HELPER:addEventHandler(event_name, callback, resource_name)
event_handler_api:addSourceToCallback().doNotAddSourceToCallback()
New since version 0.35.0
For server side only. Do not add the source as first argument to the callback (default).
Returns NssLibsSharedHelperEventHandlerApi — the event handler instance.
local event_name = 'your_event_name'
local resource_name = GetCurrentResourceName()
local callback = function(...)
print('Event ' .. tostring(event_name) .. ' for ' .. tostring(resource_name) .. 'is triggered:', ...)
end
local event_handler_api = SERVER_HELPER:addEventHandler(event_name, callback, resource_name)
event_handler_api:doNotAddSourceToCallback().enable()
Enables the event handler so all registered callbacks will be called when the event is triggered.
Returns NssLibsSharedHelperEventHandlerApi — the event handler instance.
event_handler_api:disable()
TriggerEvent('your_event_name', 'Hello World 1')
-- Output: No output because the event handler is disabled
event_handler_api:enable()
TriggerEvent('your_event_name', 'Hello World 2 ')
-- Output: "Event your_event_name for your_resource_name is triggered: Hello World 2".disable()
Do the opposite of enable().
INFO
Disabled event handlers are still existing and are registered in the system but will not be called when the event is triggered.
Returns NssLibsSharedHelperEventHandlerApi — the event handler instance.
event_handler_api:enable()
TriggerEvent('your_event_name', 'Hello World 2 ')
-- Output: "Event your_event_name for your_resource_name is triggered: Hello World 2"
event_handler_api:disable()
TriggerEvent('your_event_name', 'Hello World 1')
-- Output: No output because the event handler is disabled.isEnabled()
Returns boolean — true if the event handler is enabled. Otherwise false.
event_handler_api:disable()
local is_enabled = event_handler_api:isEnabled()
print(is_enabled) -- false
event_handler_api:enabled()
is_enabled = event_handler_api:isEnabled()
print(is_enabled) -- true.isDisabled()
Returns boolean — true if the event handler is disabled. Otherwise false.
event_handler_api:disable()
local is_disabled = event_handler_api:isDisabled()
print(is_disabled) -- true
event_handler_api:enabled()
is_disabled = event_handler_api:isDisabled()
print(is_disabled) -- false.destroy()
Removes the event handler from the system.
INFO
Destroyed event handlers does not exist anymore and are not registered in the system anymore. They can not be re-enabled.
Returns nothing.
TriggerEvent('your_event_name', 'Hello World 1')
-- Output: "Event your_event_name for your_resource_name is triggered: Hello World 1"
Citizen.Wait(1000)
event_handler_api:destroy()
TriggerEvent('your_event_name', 'Hello World 2')
-- Output: No output because the event handler is destroyed
Citizen.Wait(1000)
event_handler_api:enable()
TriggerEvent('your_event_name', 'Hello World 3')
-- Output: No output because the event handler is destroyed and can not be re-enabled.addAdditionalCallback(callback)
| Param | Type | Default | Description |
|---|---|---|---|
callback | function | — | The additional callback to add. If it returns false, subsequent callbacks will not be called |
Returns NssLibsSharedHelperEventHandlerApi — the event handler instance.
local additional_callback = function(...)
print('Additional callback:', ...)
end
event_handler_api:addAdditionalCallback(additional_callback)
TriggerEvent('your_event_name', 'Hello World')
-- Output:
-- "Event your_event_name for your_resource_name is triggered: Hello World" because of the first callback that created the event handler
-- "Additional callback: Hello World".getEventHandlerReference()
Returns any — the original event handler reference.
local event_handler_reference = event_handler_api:getEventHandlerReference()
print(event_handler_reference) -- (some reference).getUid()
Returns number — the unique id of the event handler api instance.
local event_handler_uid = event_handler_api:getUid()
print(event_handler_uid) -- (some unique id)NssLibsSharedHelperCallbackHandlerCbApi
The following methods uses the following base structure for the examples:
local callback = function(a, b, c)
print(a, b, c)
end
local resource_name = GetCurrentResourceName()
local callback_api = SERVER_HELPER.createCallbackApi(callback, resource_name).enable()
Enables the callback so if called it will be executed (except the callback was destroyed).
Returns NssLibsSharedHelperCallbackHandlerCbApi — the callback api instance.
callback_api:disable()
callback_api:call(1, 2, 3)
-- Output: No output because the callback api is disabled
callback_api:enable()
callback_api:call(1, 2, 3)
-- Output: "1, 2, 3".disable()
Disables the callback so if called it will not be executed.
INFO
Disabled callback apis are still existing and are registered in the system but will not be called when the callback api is called.
Returns NssLibsSharedHelperCallbackHandlerCbApi — the callback api instance.
callback_api:disable()
callback_api:call(1, 2, 3)
-- Output: No output because the callback api is disabled
callback_api:enable()
callback_api:call(1, 2, 3)
-- Output: "1, 2, 3".isEnabled()
Returns boolean — true if the callback api is enabled (and not destroyed).
callback_api:enable()
print(tostring(callback_api:isEnabled())) -- true
callback_api:disable()
print(tostring(callback_api:isEnabled())) -- false.isDisabled()
Returns boolean — true if the callback api is disabled (or destroyed).
callback_api:disable()
print(tostring(callback_api:isDisabled())) -- true
callback_api:enable()
print(tostring(callback_api:isDisabled())) -- true.isDestroyed()
Returns boolean — true if the callback api is destroyed.
callback_api:destroy()
print(tostring(callback_api:isDestroyed())) -- true.getResourceName()
Returns string — the resource name of the callback api.
local resource_name = callback_api:getResourceName()
print(resource_name) -- 'resource_name_of_the_owning_resource'.getUid()
Returns number — the unique identifier of the callback api.
local uid = callback_api:getUid()
print(uid) -- 'uid_of_the_callback_api'.destroy()
Destroys the callback api, so it can not be used anymore.
Returns NssLibsSharedHelperCallbackHandlerCbApi — the callback api instance.
callback_api:destroy().onDestroy(on_destroy_callback)
| Param | Type | Default | Description |
|---|---|---|---|
on_destroy_callback | function | — | The callback to call when the callback api is destroyed. If it returns true the destroy process will be canceled |
Returns NssLibsSharedHelperCallbackHandlerCbApi — the callback api instance.
local on_destroy_callback = function(callback_api)
print('Callback api destroyed', tostring(callback_api:getUid()))
-- Output: Callback api destroyed, uid_of_the_callback_api
end
callback_api:onDestroy(on_destroy_callback)
callback_api:destroy().call(...)
| Param | Type | Default | Description |
|---|---|---|---|
... | varargs? | — | The variable arguments to pass to the callback |
Calls the original callback with the given arguments. If the callback api is disabled or destroyed the callback will not be called.
Returns the result of the callback.
callback_api:call(1, 2, 3)
-- Output: "1, 2, 3"