Introduction
PIXERA Control offers LUA as an integrated scripting language. This article provides an overview of the general LUA syntax.
For advanced users:
Control LUA Style Guide
Module Style Guide
Comments
Comments are useful when coding. By using comments, the code structure will be more defined. Furthermore, it helps comprehensibility for third parties to the code:
–- comment
--[[ Multiline
Comment ]]
Invoking Functions
In Control the pixc.log() function is used rather than print() to invoke the built-in log window. The print() function does not print into PIXERA Control's log.
--In order to print something out in the log in PIXERA Control, do not use the statement:
print("Hello PIXERA")
--Use th pixc.log() statement:
pixc.log("Hello PIXERA")
Variables
Create a variable within a Control Module by using the "local" term:
local variable_name = 10
Local variables are only accessible in the script they have been created in. Besides “local”, there are also global and Module specific variables:
--global variable accessible everywhere in Control
global_variable = 1
--self.name Variables are accessible within the module.
self.module_variable = 2
Module wide variables can also be called from another Module, here only the path to the variable must be specified:
pixc.log(MyModule.module_variable)
Warning
The variable must be initialized at the time, otherwise it will be nil. It is recommended to initialize such variables in the init() function, since these are called with the autoinit property when set to true.
Tip
You can use self() to refer to your own module, or you can use self()."" to use the name of your own module as a string.
Tables / Arrays
Tables are the only data structure available in LUA that creates a format similar to Arrays and Dictionaries in other programming languages. Tables have no fixed size and can grow based on the programmer's need.
LUA uses a constructor expression “{}” to create an empty Table.
--Examples:
t = {}
t = { a = 1, b = 2 }
t.a = function() ... end
t = { ["hello"] = 200 }
--call hello inside table
t.hello
-- Remember, Arrays from other languages are also Tables.
array = { "a", "b", "c", "d" }
print(array[2]) -- "b" (one-indexed)
print(#array) -- 4 (length)
Conditionals
In LUA, an if statement is a fundamental control structure that allows you to conditionally execute a block of code based on a specified condition.
The “if” statement is used to conditionally execute a block of code when a condition is true:
if condition then
--code to execute
end
The “else” statement is used in combination with if to specify an alternative block of code to execute when the condition is false:
local temperature = 25
if temperature >= 30 then
print("It's hot outside.")
else
print("It's not hot outside.")
end
The “elseif” statement is used to test multiple conditions sequentially:
local score = 75
if score >= 90 then
print("A")
elseif score >= 80 then
print("B")
elseif score >= 70 then
print("C")
else
print("D")
end
These logical operators and conditional constructs allow you to make decisions in your LUA programs and control the flow of code based on various conditions and values.
if condition then
pixc.log("yes")
elseif condition then
pixc.log("maybe")
--else: is used to close out the multi conditional if statement:
else
pixc.log("no")
end
Loops
“while” creates a loop where the code inside will run until a certain “condition” is found true:
while condition do
--code to execute
end
“for” creates a loop that will iterate from 1 to 5 and run the code inside “i” amount of time to a max, in this case being . The loop:
for i = 1, 5 do
--code to execute
end
Similar to a for loop, this format adds a which delta can be used to manipulate steps. Int this case the delta is 2, so the loop will add 2 each run instead of 1 as it does above in a normal loop.
for i = 1, 5, 2 do
--code to execute
end
In LUA, pairs is a built-in function used to iterate over all key-value pairs in a table. It returns a key-value pair for each iteration. Here's the basic syntax:
for key, value in pairs(your_table) do
--code to execute
end
“repeat” will run the following code until the “condition” is met:
repeat
--code to execute
until condition
The while loop can be combined with a if statement. As soon as the if is met, the while loop will break:
while x do
--code to execute
if condition then break end
end
Table Lookups
Table lookups in LUA are used to access values stored within tables. Tables are versatile data structures that serve as associative arrays and can be used to store collections of key-value pairs. To perform table lookups in LUA, you typically use square brackets ([]) or dot notation. Here's how you can perform table lookups:
With Bracket Notation, you can use square brackets to access table elements by specifying the key (or index) within the brackets. For tables, keys can be of various data types, such as strings or numbers:
local person = {name = "Alice", age = 30}
print(person["name"]) -- Accessing the "name" key
print(person["age"]) -- Accessing the "age" key
You can also use variables as keys:
local key = "name"
print(person[key]) -- Accessing the "name" key using a variable
For array-like tables, you can use numeric indices:
local colors = {"red", "green", "blue"}
print(colors[2]) -- Accessing the second element, "green"
If the keys are strings without special characters (e.g., spaces), you can use Dot Notation for convenience:
print(person.name) -- Accessing the "name" key
print(person.age) -- Accessing the "age" key
Dot notation is equivalent to using bracket notation with string keys.
Tables can contain other tables, allowing for nested structures. To access elements within nested tables, you chain the lookup using multiple square brackets or dots, called Nested Table Lookups:
local contact = {name = {first = "Alice", last = "Smith"}, age = 30}
print(contact.name.first) -- Accessing the nested "first" key
If you attempt to access a key that doesn't exist in a table, LUA returns nil. To avoid errors, you can use conditional checks to ensure a key exists before accessing it.
if person.email then
print("Email: " .. person.email)
else
print("Email not found")
end
Table lookups are a fundamental concept in LUA and are used extensively for data storage and retrieval. Tables in LUA are dynamic and can store various types of values, making them a versatile data structure for a wide range of applications.
True, False, Nil
In LUA, you have three fundamental values often used in boolean expressions and program logic: true, false, and nil. Here's a brief explanation of each, along with examples:
“true” is a boolean value representing a true or positive condition. It is used to indicate that a statement or condition is true:
local isSunny = true
if isSunny then
print("It's a sunny day!")
end
“false” is the opposite of true, representing a false or negative condition. It is used to indicate that a statement or condition is false or not met:
local isRaining = false
if not isRaining then
print("No need for an umbrella.")
end
“nil” is a special value representing the absence of a value or the lack of definition. It is often used to indicate that a variable does not have a valid value.
local temperature = nil
if temperature == nil then
print("Temperature data is missing.")
end
These three values, true, false, and nil, are essential for boolean logic and conditional control in LUA programs.
Logical Operators
In LUA, logical operators and conditional logic are used to control the flow of a program. Here's a brief explanation of key logical operators and conditional constructs, along with examples.
The “and” operator returns true if both operands are true. Otherwise, it returns false.
local isSunny = true
local isWarm = true
if isSunny and isWarm then
print("It's a beautiful day!")
end
The “or” operator returns true if at least one operand is true. It returns false if both operands are false.
local isRaining = true
local hasUmbrella = false
if isRaining or hasUmbrella then
print("You might get wet.")
end
The “not” operator negates a Boolean value. It turns true into false and false into true.
local isWeekend = true
if not isWeekend then
print("It's a weekday.")
end
LUA Functions
In LUA, functions are a fundamental concept and one of the most powerful features of the language. Functions in LUA allow you to encapsulate a block of code that can be called and executed later. Here's an explanation of LUA functions:
You can define a function in LUA using the function keyword, followed by the function name, a list of parameters enclosed in parentheses, and the function body enclosed in do...end or function...end:
function greet(name)
print("Hello, " .. name)
end
You can also define anonymous functions using the function keyword without a name:
local add = function(a, b)
return a + b
end
Parameters are variables that you define in the function header and are used to pass values to the function when it is called. In the above example, name, a, and b are parameters.
To execute a function, you simply use its name followed by a pair of parentheses. If the function has parameters, you pass the arguments within the parentheses:
greet("Alice")
local result = add(5, 3)
When the greet function is called with "Alice," it prints "Hello, Alice." The add function returns the sum of its arguments, which is assigned to the result variable.
Functions in LUA can return values using the return statement. A function can return one or more values. If no return statement is used, the function returns nil.
function addAndSubtract(a, b)
local sum = a + b
local difference = a - b
return sum, difference
end
local result1, result2 = addAndSubtract(8, 3)
In this example, the "addAndSubtract" function returns both the sum and the difference of the provided arguments. When you call the function, you can capture these values into separate variables.
Functions in LUA have their own local Scope. This means that variables defined within a function are typically local to that function and do not interfere with variables outside the function. However, you can also access global variables from within a function.
LUA supports Closures, which means that functions can capture and access variables from their surrounding scope. This is a powerful feature for creating flexible and reusable code.
LUA functions are highly flexible and are used for a wide range of purposes, including code organization, encapsulation, reusability, and creating complex algorithms. They play a crucial role in LUA programming and are used extensively in various LUA libraries and frameworks.
# - Operator
In LUA, the “#” operator, also known as the "length operator," is used to determine the length of an array (a table with sequential integer keys starting from 1). It returns the number of elements in the array, counting from 1 up to the first nil value. Here's how the # operator works:
local colors = {"red", "green", "blue"}
local length = #colors
print("The length of the array is " .. length) -- Output: The length of the array is 3
In this example, the “#” operator is used to calculate the length of the colors array, which has three elements. The result is assigned to the length variable, and it is printed to the console.
It's important to note that the “#” operator is most used for arrays with sequential integer keys starting from 1. For tables with non-sequential or non-integer keys, the “#” operator may not provide the expected results, as it counts up to the first nil value, which may not accurately represent the logical length of the table.
In LUA, the “#” operator is a convenient way to obtain the length of arrays, but it should be used with caution and is not suitable for all table types.
Arithmetic Operators
In LUA, arithmetic operators are used to perform mathematical operations on numeric values. LUA supports several standard arithmetic operators for addition, subtraction, multiplication, division, and more. Here are the common arithmetic operators in LUA:
Addition is done using “+”, and adds two numbers together:
local sum = 5 + 3 -- sum is now 8
Subtraction is done using “-”, and subtracts one number from another:
local difference = 10 - 4 -- difference is now 6
Multiplication is done using “*”, and multiplies two numbers:
local product = 3 * 5 -- product is now 15
Division is done using “/”, and divides one number by another:
local quotient = 20 / 4 -- quotient is now 5
Modulus is done using “%”, and returns the remainder when one number is divided by another:
local remainder = 13 % 5 -- remainder is 3
Exponentiation is done using “^”, and raises one number to the power of another:
local result = 2^3 -- result is 8
These arithmetic operators can be combined and used in complex expressions to perform more advanced calculations in LUA. Additionally, LUA follows the standard operator precedence rules, where multiplication and division take precedence over addition and subtraction. You can use parentheses to change the order of evaluation in complex expressions.
Here's an example of a more complex expression:
local result = (5 + 3) * 2 / (4 - 2) -- result is 16
This expression first adds 5 and 3, then multiplies the result by 2, and finally divides it by the difference between 4 and 2.
Tip
The pixc.callRefs function can be used with arithmetic operators. Let's assume you want to modify incoming data from an external source. pixc.callRefs(val*2) will multiply the sent out value by 2.
PIXERA 2.0.223 | 22. January 2025 | CL