Introduction to Lua Programming

Written By: S Kokila

- 31 Aug 2007 -
















Description: Lua is a powerful, light-weight programming language designed for extending applications. Coupled with it being relatively fast and having a very lenient license, it has gained a following among game developers for providing a viable scripting interface. It has been used in games such as World of Warcraft and Far Cry, and in applications such as Adobe Photoshop Lightroom and Snort.

  1. What is Lua?
  2. Getting Started
  3. Identifiers, Types, and Values
  4. Variables and Expressions
  5. Operators
  6. Statements and Assignments
  7. Control Structures
  8. File I/O

Statements

Like many programming languages, Lua supports a conventional set of statements for assignment, control structures, function calls, variable declarations. In addition, Lua supports multiple assignments, table constructors and local declarations.

Assignment

Assignment statement allows you to give a value to a variable. Most programming languages allow single assignment as below:

a = 7

But, Lua allows multiple assignments, that is, a list of variables can be assigned with a list values in one statement. Consider the example here:

a, b, c = 1, 7, "hello"

Here a is assigned 1, b gets 7 and c gets "hello". The lists on either side of = are separated by comma. Lua evaluates all the expressions before performing assignment. For example, in

i = 3
i, a[i] = i+1, 20

20 is assigned to a[3], without affecting a[4]. This is because, the i in a[i] is evaluated before it is assigned to 4. Similarly, the statement

x, y = y, x

swaps the values of x and y.

Now, what happens if the number of values in the list is not equal to the number of variables? In that case, Lua adjusts the number of values to the number of variables. When the number of values is less than the list of variables, the list of values is extended with as many nil's as needed. Similarly, when the length of the list of values is more than the list of variables, the excess values are discarded or thrown away.

-- Multiple Assignments
a, b, c = 1, true, 5
print(a,b,c)             -- 1 true 5
a, b, c = 10
print(a,b,c)             -- 10 nil nil
a, b, c = 1, 2, 3, 4        -- 4 is discarded
print(a,b,c)             -- 1 2 3 

In Lua, a function call can return multiple values. So when a function call is placed in the list of values, the return values are adjusted depending on the position of the function call in the list.

<< Previous

Next >>