Building the Foundations: Lua

By | August 16, 2013

We now return to Lua programming on The Dark Energy Blog.

Let’s get started in learning Lua.

To start, Lua has 8 basic types: nil, boolean, number, string, userdata, function, thread, and table.

Any non-assigned variable, by default, will output nil in the Lua interpreter.

Lua typically uses true and false as the primary booleans, but any value may represent a condition. For example, false and nil are False, and anything else is True. 0 and empty string, in conditional tests, are interpreted as True in Lua.

Because programming language requires a decent amount of quantitative skill, I hope you know what a number is. But certainly, you can type in the following line of code to figure this out:

print(type(32))

Your Lua interpreter will return the following:

number

Now, let’s talk about strings.

What’s different about Lua is that you need to create a new string with desired modifications in order to actually “change” the string. The following example will help demonstrate this idea.

a = "python program"
b = string.gsub(a, "program", "programme")
print(a)
print(b)

One will print the American spelling convention of “python program” while the other will print the British spelling convention of “python program”.

Another thing to mention is that in Lua, you can use certain escape sequences. There are certain effects to doing this, as you can see in the following example below.

print("one line\nnext line\n\"in quotes\", 'in quotes'")
print('a backslash inside quotes: \'\\'')
print("a simpler way: '
\'")

The first line of code prints the following:

one line
nextline
"in quotes", 'in quotes'

The second line of code returns:

a backslash inside quotes: '\'

And the third line of code returns:

a simpler way: '\'.

Another good thing about Lua is the automatic conversions between number and string. The following code illustrates my point.

print ("34" + 3)
print("34+5")
print("34"/"2")
print("jade" + 3)

And your Lua interpreter returns:

37
"34+5"
17
error

The last line prints an error because you can’t convert “jade” into a number. And when Lua finds a number when it expects a string, the interpreter converts into a string. Like:

print(20 .. 90)

And you get 2090.

The following lines of code show how you could possibly change a string to a number, and vice versa. This is more explicit.

line = io.read()
n = tonumber(line)
if n == nil then
error(line .. " is not a valid number")
else
print(n*2)
end

Note that in the actual command line, after you print

line = io.read()

The Lua interpreter will expect you to enter a string, preferably containing quantitative information. Otherwise your interpreter will return an error.

Now, let’s try the reverse way around. Let’s look at the following lines of code.

print(tostring(10) == "10")
print(10 .. "" == "10")

And you get:

True
True

The last big thing to discuss is tables. We now try our hand at creating some tables. Begin the process by entering this line of code:

a = {}

This builds the foundations for creating tables in Lua.

Now…

a = {}
k = "x"
a[k] = 77
a[34] = "ACI"
print(a["x"])

Looking at these few lines of code, we enter them into the interpreter, and we get:

77

Now, let’s add the following lines of code to what we have so far.

k = 34
print(a[k])
a["x"] = a["x"] + 1
print(a["x"])

The Lua interpreter returns the following:

ACI
78

To show that you can use variables a and b interchangeably, let’s look at the following lines of code:

a = {}
a["x"] = 33
b = a
print(b["x"])
b["x"] = 90
print(a["x"])
a = nil
b = nil

Your interpreter should return:

33
90

The following lines of code

a = nil
b = nil

help to clear up memory.

Now, to accommodate new entries…

Let’s look at the following lines of code:

a = {}
for i=1,300 do a[i] = i*3 end
print(a[3])
a["x"] = 73
print(a["x"])
print(a["z"])

Your Lua interpreter will then return:

9
73
nil

When you input

print(a["z"])

You get

nil

because you didn’t assign any value (string, number, etc.) to a["z"] to begin with.

In representing records, you can simplify the coding process by entering

a.x=33
print(a.x)
print(a.y)

And you get the same results in your interpreter.

For beginners, it’s easy to assume a.x = a[x]. Don’t fall into this trap! a.x and a[x] are not the same thing. For one thing, a.x is equivalent to a["x"]. And the two represent different things. One is indexed by a string, while the other is indexed by a variable. The following lines of code help to illustrate the point:

a = {}
x = "z"
a[x] = 90
print(a[x])
print(a.x)
print(a.y)

Try that in the Lua interpreter, and this should help understand why a.x isn’t equal to a[x].

Now, onto the conventional arrays. Just use a table with integer keys. As shown:

a = {}
for i=1,90 do
  a[i] = io.read()
end

The first non-initialized index will show nil, so you can use this to represent the end of an array. The following lines of code

for i,line in ipairs(a) do
   print(line)
end

will print the first however many lines you set in the previous set of code denoted earlier in your Lua interpreter.

Another coding experiment:

i = 33
j = "33"
k = "+33"
a = {}
a[i] = 33
a[j] = "33"
a[k] = "+33"
print(a[j])
print(a[k])
print(a[tonumber(j)])
print(a[tonumber(k)])

Try that and see what you get in your Lua interpreter.

I’ll discuss functions, user data, and threads later on in the Lua series. It will get more fun as time moves along. Until then, good bye!

Leave a Reply

Your email address will not be published. Required fields are marked *