View Categories

toolstar® Lua-Skript API

Mit der Lua-Script API in toolstar®testLX, toolstar®testWIN, toolstar®shredderLX und toolstar®shredderWIN können Sie eigene Lua-Skripte erstellen um den Ablauf des Programms zu beeinflussen. Die bereitgestellten Funktionen bieten Ihnen unter anderem die Möglichkeit eigene Dialogs anzuzeigen, in den Ablauf eines Dauertests einzugreifen oder sogar Daten von einer HTTP-API zu laden oder an diese zu senden, um diese Daten im Test zu verwenden oder danach in Ihr ERP zu integrieren.

Support, Consulting & Entwicklung

Die Lua-Skript API kann von Ihnen selbstständig verwendet und integriert werden. Jedoch stellt toolhouse keinen Support für selbst erstellte Skripte zur Verfügung. Gerne können Sie sich bei uns für Ihren individuellen Fall ein Angebot einholen. Dazu zählen auch Erweiterungen der Skript-API. Sollten Sie technische Fehler in der Dokumentation oder der Lua-API finden, werden diese selbstverständlich von uns behoben und fallen unter den klassischen Support.

Allgemeine Funktionen

Allgemeine Funktionen zum starten von Automatisierungsskripten, anzeigen von Dialogen uvm.

=====================================================================================================================
Function: tsApp.StatusLine (string message, int isError, int timeOutMS)
=====================================================================================================================

Displays the message on the program's status line.

Parameter | Description
--------- | -----------
isError   | (optional) Set to 1 if this is an error message to be displayed in red.
timeOutMS | (optional) If greater than 0, the message will disappear after the specified milliseconds.
=====================================================================================================================
Function: tsApp.RunScript (string filename, int flags)
=====================================================================================================================

Starts a ttsx script with the given filename.
Note that the script is not loaded directly from the file at this point, but searched in the scripts that were already loaded; thus, depending on your paths, you may not need to specify the full path here.

Note: Do not use an automatic reboot in the ttsx script if you want to continue the Lua script after the ttsx script, this constellation isn't supported yet.

####################################################### Flags #######################################################

(optional) Set to 0 or `tsApp.runNormal` for normal execution (default); the script's options will determine whether a result will be displayed on screen.

Set to `tsApp.runWithoutResultDisplay` to never show the result on screen.

################################################### Return Value ####################################################

Returns two results `reason, result` once the script has finished:

###################################################### Reason #######################################################

Value                       | Description
--------------------------- | -----------
negative                    | The script couldn't be started at all (e.g. file not found, file damaged).
tsApp.reasonComplete (0)    | The script completed normally (all specified runs performed).
tsApp.reasonAbortByUser     | The user aborted the script.
tsApp.reasonExternalProgram | An external program was configured to abort the script under certain conditions that occured.
tsApp.reasonTime            | The script's duration is set to a specific time and that has expired.
tsApp.reasonErrors          | The configured maximum number of errors caused the script to stop.
tsApp.reasonLuaScript       | The script was stopped from your `tsRunningHook` (default value)

###################################################### Result #######################################################

The total result as it is also reported in the hierarchical report.

Value                              | Description
---------------------------------- | -----------
tsApp.resultNotRun (0)             | No test was perfomed.
tsApp.resultNotPresent             | No device to be tested is present.
tsApp.resultNotInMode              | No device to be tested can be tested in this mode/operating system.
tsApp.resultAbortUser              | No test was completed, user aborted.
tsApp.resultAbortError             | No test was completed, aborted due to number of errors.
tsApp.resultPartial                | No test was completed.
tsApp.resultPass                   | Tests passed.
tsApp.resultPassUser               | Tests passed; only interactive tests were performed.
tsApp.resultFail                   | Tests failed.
tsApp.resultError                  | same as resultFail
tsApp.resultFailUser               | Tests failed; only interactive tests were performed.
tsApp.resultAbortUserErr           | Aborted, errors occured.
tsApp.resultFail_LastPass          | Tests failed, but the last run passed.
tsApp.resultFailUser_LastPass      | Tests failed (interactive), but the last run passed.
tsApp.resultFail_LastAbortUser     | Tests failed, last run aborted by user.
tsApp.resultFailUser_LastAbortUser | Tests failed (interactive), last run aborted by user.
=====================================================================================================================
Function: tsApp.IsErrorResult (int result)
=====================================================================================================================

A convenience function returning a boolean value, true if the result is one of the test error results.
=====================================================================================================================
Function: tsApp.IsTestedResult (int result)
====================================================================================================================

A convenience function returning a boolean value, true if the result means something has been tested, i.e. resultAbortUser and following.
=====================================================================================================================
Function: tsApp.StopScript (int reason, int result)
=====================================================================================================================

Only available from your tsRunningHook function while a script is running, obviously.

Set reason to one of the `tsApp.reason...` values (see above). You may probably want to use reasonLuaScript.

Set result to 0 to keep the regular total result; set it to any `tsApp.result...` except resultNotRun to override the total result.
=====================================================================================================================
Function: tsApp.CurrentScript ()
=====================================================================================================================

Returns the filename (without path) of the current script, or nil if none is running.
=====================================================================================================================
Function: tsApp.Sleep (int seconds)
=====================================================================================================================

Pause for the specified number of seconds (but still keeping the program responsive).
=====================================================================================================================
Function: tsApp.SetExitAction (int action)
=====================================================================================================================

Tell the main program how to exit when your Lua script ends. If you don't set an action, you just remain in the program.

Value                    | Description
------------------------ | -----------
tsApp.exitRemain (0)     | Just remain in the program.
tsApp.exitExit           | Exit the program.
tsApp.exitRestartProgram | Exit and restart the program.
tsApp.exitPrompt         | Exit to the console prompt (self-booting Linux only).
tsApp.exitReboot         | Reboot the system.
tsApp.exitPowerOff       | Shut down the system.
tsApp.exitUefi           | Reboot into UEFI Setup.
=====================================================================================================================
Function: tsMessageBox.Show (string caption, string message, int type)
=====================================================================================================================

Shows a message box with the specified caption, message, and type. The message can contain simple HTML tags such as `<b>...</b>`, `<i>...</i>` and `<br>`; if it doesn't contain HTML, the newline character \n can also be used for line breaks.

###################################################### Type #########################################################

This is a combination of one of the button type constants and optionally one of the icon constants;
combine them with the binary OR operator `|`, e.g. `tsMessageBox.Ok | tsMessageBox.iconError`.

	tsMessageBox.Ok               -- default
	tsMessageBox.OkCancel
	tsMessageBox.Cancel
	tsMessageBox.AbortRetryIgnore
	tsMessageBox.AbortRetry
	tsMessageBox.RetryCancel
	tsMessageBox.YesNoCancel
	tsMessageBox.YesNo
	tsMessageBox.iconQuestion
	tsMessageBox.iconExclamation
	tsMessageBox.iconWarning      -- same as iconExclamation
	tsMessageBox.iconInformation
	tsMessageBox.iconError
	tsMessageBox.iconStop         -- same as iconError
	tsMessageBox.iconBulb
	tsMessageBox.iconIdea         -- same as iconBulb

#################################################### Return Value ###################################################

Returns an integer telling the button that the user pressed:

	tsMessageBox.returnOk
	tsMessageBox.returnCancel
	tsMessageBox.returnAbort
	tsMessageBox.returnRetry
	tsMessageBox.returnIgnore
	tsMessageBox.returnYes
	tsMessageBox.returnNo
=====================================================================================================================
Function: tsMessageBox.GetString (string caption, string message, string label, int type)
=====================================================================================================================

Shows a string input box with the specified caption, message, label for the input field (can be empty), and type. The type values are the same as for `tsMessageBox.Show`.

################################################### Return Value ####################################################

Returns two results `button, value`:
`button` is the same as the return value for `tsMessageBox.Show`, and `value` holds the string the user entered, or `nil` if the user cancelled the dialog.
=====================================================================================================================
Function: tsMessageBox.GetPassword (string caption, string message, string label, int type)
=====================================================================================================================

Same as `tsMessageBox.GetString` except that the input is not visible on the screen.
=====================================================================================================================
Function: tsMessageBox.Select (string caption, string message, string label, int type, array options)
=====================================================================================================================

Shows a drop-down box with the specified caption, message, label (can be empty), type, and available options for the user, which should be of the form `{ "foo", "bar or something", 123, "or pick this" }`. The type values are the same as for `tsMessageBox.Show`.

################################################### Return Value ####################################################

Returns two results `button, index`: 
`button` is the same as the return value for `tsMessageBox.Show`, and `index` holds the index of what the user selected, starting at 1.
=====================================================================================================================
Function: tsTestInfo.Get (int which)
=====================================================================================================================

Returns a string with the desired info, or an empty string (`""`) if none is set. You can use this to request data from a remote location by using user input data as parameters. The user is typing in the customized article number at start by hand and at the end you use this information's to push the data to your ERP or any other system.

###################################################### Which ########################################################

	tsTestInfo.pcName
	tsTestInfo.pcSN
	tsTestInfo.testerName
	tsTestInfo.companyName
	tsTestInfo.caption1
	tsTestInfo.caption2
	...
	tsTestInfo.caption40
	tsTestInfo.comment1
	tsTestInfo.comment2
	...
	tsTestInfo.comment40
	tsTestInfo.logo

Note: The numeric values of these constants have changed in Nov 2023, but you can still use `caption1+1`, `caption1+2`, etc. for the captions 2, 3, etc., and likewise for the comments.
=====================================================================================================================
Function: tsTestInfo.Set (int which, string newValue)
=====================================================================================================================

Sets the desired info; see `tsTestInfo.Get` for `which`.
=====================================================================================================================
Function: tsScript.GetAtStart (int which)
=====================================================================================================================

Available only during stageStart in tsRunningHook (see below). Get current int value for `which` (or `nil` for an invalid which).

###################################################### Which ########################################################

	tsScript.askDuration
	tsScript.askTestInfo
	tsScript.askReportNames
	tsScript.askMinMax
	tsScript.modalOverview      --0=none, 1=one-page, 2=standard, 3=extensive, 4=support
=====================================================================================================================
Function: tsScript.SetAtStart (int which, int value)
=====================================================================================================================

Available only during stageStart in tsRunningHook (see below). Sets the new value for `which` (see above). Use this function to conditionally enable a dialog at the start or not. For example:

Fetch data via HTTP-API by using the serial of the device. If you get data, set the data into the PC & Tester-Info and use tsScript.SetAtStart (tsScript.askTestInfo, 0) to disable the dialog. If you did not get any data via your HTTP-API, enable the dialog with tsScript.SetAtStart (tsScript.askTestInfo, 1) and let the user input the values.
=====================================================================================================================
Function: tsScript.GetMinMax (int which)
=====================================================================================================================

Available only during stageAsked in tsRunningHook (see below).

Important: These all depend on the corresponding test settings. You cannot activate something here that isn't set in a test, you can only override its number.

Get current int value for `which` if any is set; returns `nil` if none is set.

###################################################### Which ########################################################

	tsScript.minSerialPorts
	tsScript.minParallelPorts
	tsScript.minUSBTestPlugs
	tsScript.minNetworkInterfaces
	tsScript.minMemoryModules
	tsScript.minMemoryMB
	tsScript.minRemovableDisks
	tsScript.minHardDisks		--for tests referring to HDDs and SSDs
	tsScript.minHardDisksHDD	--for tests with "HDDs only" set
	tsScript.minHardDisksSSD	--for tests with "SSDs only" set
	tsScript.minLogicalVolumes	--Windows only
	tsScript.minOpticalDisks	--CD/DVD/etc.

	tsScript.maxSerialPorts
	tsScript.maxParallelPorts
	tsScript.maxRemovableDisks
	tsScript.maxHardDisks		--for tests referring to HDDs and SSDs
	tsScript.maxHardDisksHDD	--for tests with "HDDs only" set
	tsScript.maxHardDisksSSD	--for tests with "SSDs only" set
	tsScript.maxLogicalVolumes	--Windows only
	tsScript.maxOpticalDisks	--CD/DVD/etc.
=====================================================================================================================
Function: tsScript.SetMinMax (int which, int value)
=====================================================================================================================

Available only during stageAsked in tsRunningHook (see below). Sets the new value for `which` (see above).
=====================================================================================================================
Function: tsReport.GetCount ()
=====================================================================================================================

Returns an integer with the number of configured reports, including the screen output and inactive reports.
=====================================================================================================================
Function: tsReport.GetActive ()
=====================================================================================================================

Returns an integer with a bitfield of the active reports. (Bit 0 is always set for the screen output.)
=====================================================================================================================
Function: tsReport.SetActive (int which, bool active)
=====================================================================================================================

Sets the specified report (`which`, which must be 1 or higher; the screen report, no. 0, cannot be modified) to active or inactive (`active` is optional and defaults to true).
=====================================================================================================================
Function: tsReport.GetTarget (int which)
=====================================================================================================================

Retrieves the target of a report, which can be one of the following:

	tsReport.targetScreen
	tsReport.targetFile
	tsReport.targetEmail
	tsReport.targetFTP
=====================================================================================================================
Function: tsReport.GetFormat (int which)
=====================================================================================================================

Retrieves the format of a report, which can be one of the following:

	tsReport.formatTextTab           --tables only use a tab character
	tsReport.formatTextNice          --nicer, more human-readable table formatting
	tsReport.formatHTML
	tsReport.formatPDF
	tsReport.formatXML
	tsReport.formatJSON
=====================================================================================================================
Function: tsReport.SetFormat (int which, int newFormat)
=====================================================================================================================

Changes the format of a report. For example from TXT to PDF
=====================================================================================================================
Function: tsReport.GetFilename (int which)
=====================================================================================================================

Gets the file name where applicable (file name for file and FTP targets, attachment file name for e-mail), or `nil` otherwise. This is the original file name that may include special functions with `%`.
=====================================================================================================================
Function: tsReport.SetFilename (int which, string newFilename)
=====================================================================================================================

Sets the (original) file name where applicable. The original filename is the name with the variables like %S and so on still set and not evaluated.
=====================================================================================================================
Function: tsReport.GetFinalFilename (int which)
=====================================================================================================================

Gets the actually used file name after all special functions with `%` have been evaluated, where applicable (active reports only).

For file targets with permanent writing, it's valid from stageTop on, but note that the file is open during the entire script run. For other targets with file names, it's valid in stageEnd only; however for emails, the attached file doesn't actually exist locally.

You can use this at the end of a script to get the filename with the JSON data to parse and send it to a remote location like HTTP-API.
=====================================================================================================================
Function: tsReport.AddText (string text, int toWhich, string headline)
=====================================================================================================================

Adds a text to the desired report(s) specified by the bitfield in `toWhich`. If `toWhich` (optional) is 0 or omitted, the text is written to all reports.

If `headline` (optional) is specified, this will be the big section headline above the text (similar to "System Overview", "Results", etc.)
=====================================================================================================================
Function: tsLog (string text)
=====================================================================================================================

Writes text to the program log (tslog.txt, also accessible in the Settings menu). A newline character is automatically appended. The Log can be found at C:\Users\[Username]\AppData\Local\Temp\tslog.txt in Windows and /tmp/tslog.txt in self booting toolstar®-LX software.
=====================================================================================================================
Function: tsApp.tsBase64Encode (string)
=====================================================================================================================

Encodes the given string to a base64 string. Usefull to decode data from Web-APIs.
=====================================================================================================================
Function: tsApp.tsBase64Decode (string)
=====================================================================================================================

Decodes the given base64 string into plain text. Usefull to encode data for Web-APIs.

Funktionen zur Abfrage von Systeminformationen

Mit den Funktionen innerhalb des tsSystem-Namespace können Sie verschiedenen Systeminformationen der lokalen Hardware abrufen. Wie zum Beispiel Seriennummern, PCI-IDs, Grafikkarten oder Festplatten. Nutzen Sie zum Beispiel `tsSystem.GetDMI (tsSystem.dmiSystemSerial)` um die Seriennummer des aktuellen Geräts in einer HTTP-API Anfrage zu verwenden. Oder fragen Sie alle aktuellen Laufwerke mit `tsSystem.GetDrives (tsSystem.drvHarddisk)` ab und nutzen Sie `tsSystem.GetDriveInfo (“/dev/sda”)` um mehr über ein Laufwerk zu erfahren. Diese Informationen können Sie dann nutzen um zum Beispiel ein spezielles Skript via `tsApp.RunScript (“MyCustomScript.ttsx”, tsApp.runNormal)` für NVMe-Laufwerke zu starten.

=====================================================================================================================
Function: tsSystem.GetDMI (int which)
=====================================================================================================================

Retrieves a value from the system's SMBios/DMI.

These values for `which` return a string (an empty string `""` if the value doesn't exist):

	tsSystem.dmiBiosName
	tsSystem.dmiBiosVersion
	tsSystem.dmiBiosDate
	tsSystem.dmiBoardVendor
	tsSystem.dmiBoardName
	tsSystem.dmiBoardSerial
	tsSystem.dmiBoardVersion
	tsSystem.dmiSystemVendor
	tsSystem.dmiSystemName
	tsSystem.dmiSystemSerial
	tsSystem.dmiSystemVersion
	tsSystem.dmiSystemUuid
	tsSystem.dmiMemoryInfo  -- single-line memory information as in one-page system overview
	tsSystem.dmiMemoryType  -- e.g. "DDR3"

These values for `which` return an integer:

	tsSystem.dmiMemoryModules  -- number of modules
	tsSystem.dmiMemorySlots    -- number of slots, including empty slot
=====================================================================================================================
Function: tsSystem.GetCPUInfo (int which)
=====================================================================================================================

Retrieves information about the CPU.

These values for `which` return a string (an empty string `""` if the value doesn't exist):

	tsSystem.cpuOwnname
	tsSystem.cpuManufacturer

These values for `which` return an integer:

	tsSystem.cpuThreadsTotal
	tsSystem.cpuWinOnArm	-- 0 or 1
=====================================================================================================================
Function: tsSystem.GetGraphicsInfo (int index, int which)
=====================================================================================================================

Retrieves information about the GPU(s). `index` starts at 0 for the first GPU.

These values for `which` return a string (an empty string `""` if the value doesn't exist):

	tsSystem.graPciPath	-- 00000000:01:02.3 or 1/2/3 depending on global setting
	tsSystem.graClassName
	tsSystem.graType	-- iGPU or dGPU
	tsSystem.graVendor
	tsSystem.graDevice
	tsSystem.graSubvendor
	tsSystem.graSubdevice

These values for `which` return an integer:

	tsSystem.graClassCode
	tsSystem.graMemory	-- MB
=====================================================================================================================
Function: tsSystem.GetDrives (int which)
=====================================================================================================================

Retrieves a list of physical drive device names for the desired type in `which`:

	tsSystem.drvRemovable
	tsSystem.drvHarddisk
	tsSystem.drvOptical

#################################################### Return Value ###################################################

Returnes a (1-based) array of device names (such as /dev/sdb in Linux), or an empty table if no drive of the desired type is present.
=====================================================================================================================
Function: tsSystem.GetDriveInfo (string dev)
=====================================================================================================================

Retrieves information about the drive similar to the drive overview in the program. `dev` is one of the device names you got from GetDrives.

#################################################### Return Value ###################################################

Returns a table with the following keys, or `nil` for a non-existent device name.

	"devName"	-- the same as the input
	"devID"
	"type"		-- string as in overview (translated)
	"interface"	-- string as in overview (translated)
	"name"
	"serial"
	"serialUSB"	-- for drives behind USB
	"isSSD"		-- 0 or 1
	"capacity"	-- string like "123 GB" or "empty"
	"sectors"	-- int
	"sectorSize"	-- int (bytes)

More may be added in the future as required.

Autostart-Funktion

If your script provides a function tsAutostart ()and you choose the Lua autostart option on the "Program Start" page of the Settings dialog, this function gets called at the point when the regular autostart function would be executed, or the menu would be shown. Best place to start a ttsx script.

################################################### Example code ####################################################

function tsAutostart ()
	-- Run the script MyCustomScript.ttsx with the tsApp.runNormal flag
	tsApp.RunScript ("MyCustomScript.ttsx", tsApp.runNormal)
end

Callback-Funktion während der Skriptausführung (Hooks)

If you provide a function tsRunningHook (int stage, int param)in your Lua script, it will get called during various stages while the ttsx script is running.
Note: If you start a script from initialization (not tsAutostart), the hook function must be declared above the tsApp.RunScript call, or the interpreter will not find it.
Note: stageCertificateSave will also be called after an erasure outside of a ttsx script; param is a string in this case.

=====================================================================================================================
Function: tsRunningHook (int stage, int param)
=====================================================================================================================

function tsRunningHook (stage, param)
	if stage == tsApp.stageStart then
		--tsApp.StatusLine ("Hook! stage="..string.format("0x%02x",stage)..", param="..param, 1)
	end
	if stage == tsApp.stageAsked then
		--tsApp.StatusLine ("Hook! stage="..string.format("0x%02x",stage)..", param="..param, 1)
	end
	if stage == tsApp.stageTop then
		--tsApp.StatusLine ("Hook! stage="..string.format("0x%02x",stage)..", param="..param, 1)
	end
	if stage == tsApp.stageStartingRun then
		--tsApp.StatusLine ("Hook! stage="..string.format("0x%02x",stage)..", param="..param, 1)
	end
	if stage == tsApp.stageError then
		--tsApp.StatusLine ("Hook! stage="..string.format("0x%02x",stage)..", param="..param, 1)
	end
	if stage == tsApp.stageRunEnded then
		--tsApp.StatusLine ("Hook! stage="..string.format("0x%02x",stage)..", param="..param, 1)
	end
	if stage == tsApp.stageBottom then
		--tsApp.StatusLine ("Hook! stage="..string.format("0x%02x",stage)..", param="..param, 1)
	end
	if stage == tsApp.stageEnd then
		--tsApp.StatusLine ("Hook! stage="..string.format("0x%02x",stage)..", param="..param, 1)
	end
end

###################################################### Stage ########################################################

Value                       | Description
--------------------------- | -----------
tsApp.stageStart            | The very beginning of the script; good place to modify reports or user questions.
tsApp.stageAsked            | A little later, any user questions/confirmations have been done. Modify min/max numbers here.
tsApp.stageTop              | Output has been initialized - you can now write to the top of the report.
tsApp.stageStartingRun      | A new total run is just starting; param is the number of the run, starting at 1.
tsApp.stageError            | An error result has occured in a test.
tsApp.stageCertificateSaved | An erasure certificate has been saved; param is its file name incl. path (if local copy option set: local copy's path)
tsApp.stageRunEnded         | A total run has just ended; param is the number of the run, starting at 1.
tsApp.stageBottom           | Almost the end of the script, you can still write to the bottom of the report; param is the total number of test errors.
tsApp.stageEnd              | The end of the script; all reports are saved and have their final file names; param is the total number of test errors.

JSON-Funktionen

=====================================================================================================================
JSON library functions
=====================================================================================================================

Unless disabled in the dialog (or LuaOptions bit 0 in the ini file), we include a simple public-domain JSON parser (https://gist.github.com/tylerneylon/59f4bcf316be525b30ab) that your script can use with `json = require ("json")`, offering a `json.parse (string)` function that returns (nested) Lua table with the JSON elements, plus `json.stringify (table)` for the reverse functionality.

################################################### Example code ####################################################

-- Take a JSON string and get a Lua-Table
local jsonTable = json.parse("{\"name\":\"toolhouse\", \"age\":30, \"array\":[\"Diagnostic software\"]}")

-- Take a Lua-Table and convert it into a JSON string
local jsonString = json.stringify (jsonTable)

-- Write the JSON as string to the Status-Log
tsApp.StatusLine (jsonString, 0)

HTTP-Funktionen

=====================================================================================================================
Function: tsHttp.Request (string url, string user, string pass, string postdata)
=====================================================================================================================

Performs a simple HTTP/HTTPS request to URL `url`. Use the optional `user` and `pass` parameters if Basic Authentication is required by the server. If the optional `postdata` is specified, it is used for a POST request.

#################################################### Return Value ###################################################

Returns two results `resultcode, data`.

If `resultcode` is negative, then it tells the error code from the cURL library (e.g. -6), and `data` contains the error description (e.g. "Couldn't resolve host name")". Otherwise, `resultcode` is the HTTP status code (such as 200 for OK or the infamous 404, etc.), and `data` is the server reply (which probably is an HTTP error message for non-OK results).

################################################### Example code ####################################################

-- Request data from an HTTP API and store the JSON result into a variable data, update the data and send it back
code, data = tsHttp.Request ("http://my.api.de/endpoint.json", "BasicAuthUser", "BasicAuthPw")
tsApp.StatusLine ("Got data from API: "..data, 0)
if code == 200 then
	local jsonTable = json.parse(data)
	jsonTable[1].name = "NewName"
	code, data = tsHttp.Request ("http://my.api.de/endpoint.json", "BasicAuthUser", "BasicAuthPw", json.stringify(jsonTable))
	if code == 200 then
		tsApp.StatusLine("Updated data successfully", 0)
	else
		tsApp.StatusLine ("Error updating data via HTTP-API. HTTP-Code: "..code, 1)
	end
else
	tsApp.StatusLine ("Error getting data from HTTP-API. HTTP-Code: "..code, 1)
end

Library und wieder verwendbare Blöcke von Code

Um bestimmte Code-Blöcke wieder verwendbar zu machen können mit Lua Librarys erstellt werden. Die dort enthaltenen Funktionen können dann exportiert und im Hauptskript verwendet werden. Zum Beispiel könnten Sie die Kommunikation mit Ihrer HTTP-API in einer Library “ErpApi.lua” definieren und dann gezielt einzelne Funktionen für das Hauptskript verfügbar machen.

################################################# Lib: ErpApi.lua ##################################################


local ErpApi = {}

-- Local function, not exported, only callable locally in this file
function getAuthInfo()
	-- Do stuff to get auth data like API-Keys
end

-- Exported, callable in other scripts
function ErpApi.getStuff(id)
	-- Do calling stuff and data retrieval
end

-- Export functions
return ErpApi

################################################# Main: main.lua ##################################################

ErpApi = require "ErpApi"

function ErpGetStuff()
	data, code = ErpApi.getStuff(1)
end

Nützliche Code-Blöcke für Ihre Skripte

######################################## Read all text from file into string ########################################

-- file is the path to the textual file to be read
function readAllText(file)
	local f = assert(io.open(file, "rb"))
	local content = f:read("*all")
	f:close()
	return content
end

completeTextAsString = readAllText("/testlx/testlx.ini")
############################################ Simple debug output function ###########################################

-- Write a message to the StatusLog and ProgrammLog. If isError is 1, show it as error in the StatusLog.
function debug(message, isError)
	tsLog (message)
	tsApp.StatusLine (message, isError)
end
######################################## Determinate if we are in Windows or Unix ###################################

-- Determine the platform we are running on. Useful to create scripts for testWIN and testLX in one file
function determineOsPlatform()
	if package.config:sub(1,1) == "\\" then
		return "Windows"
	elseif package.config:sub(1,1) == "/" then
		return "Unix"
	else
		return "Unknown"
	end
end

-- Utility for better readability
function isWindows()
	return determineOsPlatform() == "Windows"
end

-- Utility for better readability
function isUnix()
	return determineOsPlatform() == "Unix"
end
########################################## Mount network share in Win and Unix ######################################

-- Based on the platform mount a network share to a local dir or drive letter
function mountNetworkShare()
	if isUnix() then
		os.execute ("mkdir /LocalFolder")
		return os.execute ("mount //192.168.253.11/NetworkPath /LocalFolder -o username=User -o password=Pw")
	elseif isWindows() then
		return os.execute ("net use Z: \\192.168.253.11\NetworkPath /user:User Pw")
	else
		return -1;
	end
end

Cookie Consent mit Real Cookie Banner