Global Functions
This section describes the global functions available in Monsta’s Lua environment. These are functions that do not belong to specific modules but are available directly in Lua’s global scope. There are features for flow control, time handling, and others.
Available Functions
Section titled “Available Functions”sleep(seconds)
Section titled “sleep(seconds)”Description: Pauses script execution for a specified number of seconds.
Parameters:
seconds(number): Number of seconds to pause execution
Return: nil (does not return a value)
Example:
-- Pause for 5 secondssleep(5)print("Execução retomada após 5 segundos")signal(signal_name)
Section titled “signal(signal_name)”Description: Signals the end of script execution with a specific signal name.
Parameters:
signal_name(string): Name of the signal to be emitted
Return: Aborts script execution with the signal name
Characteristics:
-
Calls the function
_execution_doneif available in the global environment -
Always raises an error, interrupting normal execution
-
Useful for flow control and signaling states
Note: Currently, this function has a single specific use case: signaling with the name RepeatPrevValue. When a script emits this signal, the system interprets that the current collection should repeat the last valid metric value instead of producing a new data point. This is useful in situations where the data source is temporarily unavailable or the collection failed, but you do not want to interrupt the time series.
Specific usage example:
-- Try to collect a valuelocal value, err = collect_metric()if err then -- In case of failure, repeat the previous value signal("RepeatPrevValue")endwith_timeout(timeout_ms, func, ...)
Section titled “with_timeout(timeout_ms, func, ...)”Description: Executes a function with a time limit (timeout).
Parameters:
-
timeout_ms(number): Timeout in milliseconds -
func(function): Lua function to execute -
...(optional): Arguments to pass to the function
Return: Returns the result of the executed function
Example:
-- Execute a function with a 2-second timeoutlocal result = with_timeout(2000, function() -- Operation that may take long return some_long_running_operation()end)
-- Execute with argumentslocal data = with_timeout(1000, http.get, "https://api.example.com/data")
-- Handling using with_coroutine (returns result, err)local result_crit, err = with_coroutine(function() return with_timeout(500, function() -- Operation that must complete quickly return critical_operation() end)end)
if err then print("Operação excedeu o timeout de 500ms ou ocorreu um erro: " .. tostring(err))endCharacteristics:
-
Raises an error if the timeout is exceeded
-
Preserves the arguments passed to the function
-
Useful for network or I/O operations that may hang
Description: Returns the number of non-leap seconds since January 1, 1970 00:00:00 UTC (also known as the UNIX timestamp).
Parameters: None
Return: Number representing seconds since the Unix epoch
Example:
-- Get current timestamplocal current_time = now()print("Timestamp atual:", current_time)
-- Calculate operation durationlocal start_time = now()
-- Execute some operationlocal end_time = now()local duration = end_time - start_timeprint("Operação levou", duration, "segundos")Characteristics:
-
Same function available in
time.now() -
Useful for performance measurement
print(...)
Section titled “print(...)”Description: Print function that formats multiple arguments.
Parameters:
...(multiple values): Values to be printed
Return: nil (does not return a value)
Example:
print("Valor:", 42, "Status:", true, "Lista:", {1, 2, 3})Characteristics:
-
Separates multiple arguments with a tab
-
Useful for debugging
diff(lhs, rhs)
Section titled “diff(lhs, rhs)”Description: Calculates the difference between two numeric values, with special handling for counters that may rollover.
Parameters:
-
lhs(number): Current value (left-hand side) -
rhs(number): Previous value (right-hand side)
Return: Number representing the difference between the values
Behavior:
-
Calculates
lhs - rhs -
If the result is negative, emits the signal
"RepeatPrevValue" -
Used internally by
snmp.diffandwmi.difffor difference calculation on counters -
Useful for counter metrics that may rollover (such as 32- or 64-bit counters)
Example:
-- Calculate difference between counter readingslocal current_value = 4294967290 -- Valor atual (próximo do rollover de 32 bits)local previous_value = 4294967280 -- Valor anterior
local difference = diff(current_value, previous_value)-- difference = 10 (4294967290 - 4294967280)
-- Case with rollover (value decreased)local current_with_rollover = 10 -- Após rolloverlocal previous_before_rollover = 4294967295 -- Antes do rollover
local rollover_diff = diff(current_with_rollover, previous_before_rollover)-- Emite sinal "RepeatPrevValue" pois 10 - 4294967295 é negativoGlobal Variables
Section titled “Global Variables”EXEC_IDENT
Section titled “EXEC_IDENT”Description: Unique identifier of the current script execution.
Type: String
Example:
-- Use the identifier in logsprint("Execução ID:", EXEC_IDENT)
-- Include in monitoring datalocal metrics = { ident = EXEC_IDENT, timestamp = now(), value = collected_data}
-- Use as a key for storagestore.put("results_" .. EXEC_IDENT, processing_result)Characteristics:
-
Automatically defined by the environment
-
Unique for each script execution
-
Useful for tracing and correlating logs
Limitations
Section titled “Limitations”-
sleepIs Not Precise: Due to the asynchronous nature of the system,sleepmay have small variations. -
signalInterrupts Execution: Once called, normal execution is interrupted.
Example
Section titled “Example”-- Monitor a service with backoff on failure using with_coroutinelocal function monitor_with_backoff(service_url, max_attempts) local attempt = 1 local backoff = 1 -- seconds
while attempt <= max_attempts do log.info("Tentativa", attempt, "de", max_attempts)
-- with_coroutine returns (result, err) local status, err = with_coroutine(function() return with_timeout(5000, function() return check_service(service_url) end) end)
-- If there was no error (err == nil) and the service status is healthy if not err and status == "healthy" then log.info("Serviço saudável") return true else log.info("Tentativa falhou:", err or ("Status: " .. tostring(status))) end
-- Increase exponential backoff sleep(backoff) backoff = math.min(backoff * 2, 60) -- Maximum 60 seconds attempt = attempt + 1 end
-- All attempts failed return falseend
-- Run monitoringmonitor_with_backoff("https://api.example.com", 5)