The Language

From GiderosMobile
Revision as of 17:52, 10 September 2018 by Anthony (talk | contribs) (Created page with "=== Assignments and Variables === Lua is a dynamically-typed language, that is, variables don't have types, only the values. All values carry their own type. Consider the fol...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Assignments and Variables

Lua is a dynamically-typed language, that is, variables don't have types, only the values. All values carry their own type. Consider the following as an example:

MyTable = wide
width = 3; height = 1.5
area = width * height
print (area)

You can nest several lines using semicolons, but it’s optional and generally not a good programming habit as it decreases the readability of your code.Be careful not to use reserved words. Gideros Studio will complain when you use a reserved word in Lua. Consider this example:

local = 1

Since Lua is a small language, it only has 8 basic data types:

  1. nil (null)
  2. Booleans
  3. Numbers
  4. Strings
  5. Functions
  6. Userdata
  7. Threads
  8. Tables

Global variables in Lua do not need to be declared. If you want to declare a variable, just assign a value to it. Giving it a nil value removes the variable. In fact, when a variable is removed, and it’s not referenced by another variable, it’s ready to be cleared up from memory, thanks to the wonderful Lua garbage collector.

Lua can support multiple assignments. Check the following assignment:

a, b, c = 1, 2, 3

-- Easy method to swap two variables
x, y = y, z      

-- Function can return multiple values
n, m = calculate (phi, zeta)

Basic Functions

Lua has the ability to call its own functions or C functions, and it handles functions as a "data type". Note that functions can return multiple values, and you can use multiple assignments to collect these functions.

function calculate(w, d, h)
  if h > 4 then
    print ("height of the room cannot be more than 4”)
    return
  end
  volume = w * d * h
  return volume
end

-- Calculate the volume of the room
print (calculate (4,3,4))

Try the function above, this time with values 4,5,5.