Functions & Operators

Let's look at Lua functions today.

Functions



Last time I talked about scope and Lua blocks of code which are called "chunks". A function, in Lua, is a named chunk of codde using the syntax:

function name([parameters])
— code here
end


And here is an example that prints "Hello Lua" and takes no parameters:

function HelloWorld()
h = "Hello"
w = "Lua"
print(h .. " " .. w)
end


Calling a function is similar to other languages. You use the name of the function followed by any arguments in parentheses.

HelloWorld()

Here is an example that multiplies two numbers:

function MultiplyTwoNumbers(x,y)
local result = x * y
print(x .. "*" .. y .. "=" ..result)
end

MultiplyTwoNumbers(3,217)

This is what it looks like when you run it:

Screen Shot 2021-01-19 at 8.51.48 AM

The number of arguments and parameters doesn't have to match in Lua. Extra arguments are ignored. Too few arguments are passed in with a nil value. Of course, if you use the missing argument in a way that doesn't make sense, you'll get an error as in the second call to MultiplyTwoNumbers here.

Screen Shot 2021-01-19 at 8.57.27 AM

As in other languages, Lua functions can return values using a return statement.

function MultiplyTwoNumbers(x,y)
local result = x * y
local answer = x .. "*" .. y .. "=" .. result
return answer
end


print(MultiplyTwoNumbers(3,217))

Lua can also return more than a single value from within a function. Unlike other languages, this is not treated as a tuple.

function AreaAndCircumference(radius)
local area = 3.14 * radius * radius
local circumference = 2 * 3.14 * radius
return area, circumference
end

a, c = AreaAndCircumference(12.3)
print("Area:" .. a)
print("Circumference:" .. c)


Screen Shot 2021-01-19 at 9.07.18 AM

You can ignore trailing return values. So in this example I could have said:

a = AreaAndCircumference(12.3)

I haven't looked to see if there is a way to ignore leading or embedded return values.

Operators



Most of the Lua operators are standard (or familiar).
  • +
  • -
  • *
  • /
  • % (modulo)
  • ^ (exponent)
  • ==
  • ~= (not equal)
  • <
  • >
  • <=
  • >=
  • and
  • or
  • not


I've mentioned one unique operator, concatenation.
  • ..
I'll look at control structures (conditionals and loops next time.



This site does not track your information.