Contact Us

CATEGORIES

Whoops…Nothing found

Try other keywords in your search

Lua Basic Overview

 7 Minutes

 2 Likes

 2701 Views

Introduction

Pixera Control offers LUA as an integrated scripting language. This article provides a general 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 improve. Furthermore, it helps comprehensibility for third party:
 

–- comment
--[[ Multiline 
Comment ]]

Invoking Functions

In Control the pixc.log function is used rather than print to invoke to the built-in log. The print function does not print into Pixera Controls 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 option:

local variable_name = 10

 

Local variables are only accessible in the script they have been created in. Besides local there are furthermore 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 an autoinit.

 

Tipp

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 helps to create arrays and dictionaries. Tables have no fixed size and can grow based on our 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 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 basic syntax of an if statement in Lua is as follows:

 

if condition then
--code to execute
end

 

elseif: This is used to test multiple conditions sequentially:

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 a certain “condition” is active, do the “following”:

while condition do
end

 

For loop. In this example i=steps and 5 is the maximum. The loop will iterate from 1 to 5 and do "something" (for example play timelines):

 

for i = 1,5 do
end

 

Same as for loop. In addition, delta can be used to manipulate steps. 

 

for i = start, finish, delta do
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
end

 

Repeat something until the condition is met:

 

repeat
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
     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:

 

  • 1 - 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"

 

  • 2 - Dot Notation:
    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.

 

  • 3 - Nested Table Lookups:
    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:

 

local contact = {name = {first = "Alice", last = "Smith"}, age = 30}
print(contact.name.first) -- Accessing the nested "first" key

 

  • 4 - Handling Nonexistent Keys:
    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:

 

  • 1 - true:

true is a boolean value representing a true or positive condition.
It is used to indicate that a statement or condition is true.
 

Example:


local isSunny = true
if isSunny then
   print("It's a sunny day!")
end

 

  • 2 - false:

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.
 

Example:


local isRaining = false
if not isRaining then
   print("No need for an umbrella.")
end

 

  • 3 - nil:

iNl 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.
 

Example:


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.

 

Logical Operators:

and: This operator returns true if both operands are true. Otherwise, it returns false.
 

Example:


local isSunny = true
local isWarm = true
if isSunny and isWarm then
   print("It's a beautiful day!")
end

 


or: This operator returns true if at least one operand is true. It returns false if both operands are false.
 

Example:


local isRaining = true
local hasUmbrella = false
if isRaining or hasUmbrella then
   print("You might get wet.")
end


 

not: This operator negates a Boolean value. It turns true into false and false into true.
 

Example:


local isWeekend = true
if not isWeekend then
   print("It's a weekday.")
end

 

 

Conditional Statements:

if: The if statement is used to conditionally execute a block of code when a condition is true.
 

Example:


local age = 18
if age >= 18 then
   print("You are eligible to vote.")
end


 

else: The else statement is used in combination with if to specify an alternative block of code to execute when the condition is false.
 

Example:


local temperature = 25
if temperature >= 30 then
   print("It's hot outside.")
else
   print("It's not hot outside.")
end

 

elseif: The elseif statement is used to test multiple conditions sequentially.
 

Example:


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.


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:

 

  • 1 - Function Definition:
    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

 

  • 2 - FBoolean Parameters:
    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.
     
  • 3 - Function Call:
    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.

 

  • 4 - Return Values:
    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.

 

  • 5 - Scope:
    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.

 

  • 6 - Closures:
    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 +: Used to add two numbers together.

 

Example:


local sum = 5 + 3 -- sum is now 8

Subtraction -: Used to subtract one number from another.

Example:


local difference = 10 - 4 -- difference is now 6

Multiplication *: Used to multiply two numbers.

Example:


local product = 3 * 5 -- product is now 15

Division /: Used to divide one number by another.

Example:


local quotient = 20 / 4 -- quotient is now 5

 

Modulus %: Returns the remainder when one number is divided by another.

Example:


local remainder = 13 % 5 -- remainder is 3

Exponentiation ^: Raises one number to the power of another.

Example:


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.

Info

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.

pixc.callRefs  

 

 

 

 

Pixera 1.9.136 | 21. October 2023

Was this article helpful?