Learning Lua Scripting – Part 3: Variables


Part 3 of our tutorial series on the Lua scripting language.  In this tutorial we explore the variable system in Lua.

Lua uses an untyped variable declaration system.  That means that you do not need to decide on what type a variable is, just declare it with the keyword local.

Lua variables can store nil, number (floating point), strings, boolean, tables, functions, userdata, and threads.

By default, any new variable has the value of nil until given a value.

That doesn’t mean that Lua doesn’t type its variables! It does.  If you use the command type, you can see what variable type is being used in the storage:
[codebox 1]

The print command in this code example will result in “number” being displayed in the console.  All numbers are stored as double precision floating point variables.

Boolean can be a little tricky for evaluation.  If the variable has no value (or nil), it will evaluate (ie. when using if..then or while structures) to FALSE.

We will explore tables in depth later, but for now, you should know that tables are declared with the curly brackets {}:
[codebox 2]

To work with the contents of a table, you can reference the object based upon the index.  Note that table indexes start counting at 1, not 0!
Thus the above code example would output the first object in the table: “a string”

 

Resources

If you would like print resources, there are several books on Lua available.

Programming in Lua by Roberto Ierusalimschy, one of the lead architects of Lua.  Great technical intro to the language.



Lua 5.2 Reference Manual
also by Roberto Ierusalimschy, is, as the name implies, a less expensive reference manual.  Useful for the experienced coder who just needs to look up some of the details of
the language.

Lua Programming Gems by L. de Figueiredo, W. Celes, and R. Ierusalimschy is an older (2008) collection of code snippets that can be useful.


Editor –

We used the Zerobrane editor in all of our video demonstrations.

Our books:
We have several books on Corona and Amazon Lumberyard (both of which use Lua as their scripting language):
Learning Mobile Application & Game Development with Corona – Learn to program in Lua and how to make mobile apps! eTextbook for those who are new to programming.

Beginning Mobile App Development with Corona – Introduces mobile application development for those who already know how to program.

Game Design Fundamentals with Amazon Lumberyard – For those who are new 3D Game development, this eTextbook introduces how to make a game using Blender, GIMP, and Amazon Lumberyard.

The idea of writing a textbook on the Lua Scripting language has been floated to me.  While I greatly value Dr. Ierusalimschy, our styles of instruction are very different.  Leave me a comment if you would like to see a Lua Scripting textbook.

 

Next Lesson: Part 4 – Working with Strings

Recent Posts