Lua Basics

I’ve worked with a handful of scripting languages before (DCL, perl, python) but I’ve never written more than a few projects in any one.  Since you are usually doing something pretty simple with them, I typically just find a tutorial, and look up just enough to get my work done.

I’m just going to list some interesting points about the Lua language here, and if you need more information, you can search for it online.  This should be enough for you to get enough of an understanding to read basic scripts.

  • Variables are all global by default.  To declare a variable, just set it to a value – “var = 2”.  If you want to give something a local scope, declare it with “local” in front – “local var = 1”.
  • No semi-colons or anything to end a line
  • If statements look like this :  “if condition then statements end”.  Note no parenthesis around the condition.
  • == means equals, and ~= (not !=) means not equals.
  • “and” and “or” rather than “&&” and “||” for conditions.
  • To pull in another file, use “dofile(filename)”
  • Comments start with “–“, and comment blocks start with “–[[” and end with “]]–“
  • Declare functions like this – “function foo(input1, input2) statements end”
  • Functions can return 0 or more values.  You declare them all the same.
  • There are no concepts of classes or inheritance in Lua.  Instead, there are tables, which are just collections of key-value pairs.
        • The key can be anything.  If you use an integer, the table can represent an array.  If you use a string, a table can represent a dictionary.
        • The value can be a variable or a function, which we can use to simulate classes and inheritance.  I’ll go over this in the next post.
  • If you use a table as an array, it is indexed starting at 1.
  • To print out the contents of a variable, use the function “print(variable)”

Here is a sample program that demonstrates some of these points:

--adds 1 and returns it
function add(a)
  return a+1
end

global_foo = 2
local foo = 1
print(foo)
foo = add(foo)
print(foo)

if foo == 1 then
  print("this didn't work!")
elseif foo == 2 then
  print("this worked")
end

if global_foo == 2 and foo == 2 then
  print("they are the same")
end

Next post I’ll go over the syntax used to create tables, and how to simulate classes/inheritance using tables in Lua.

Leave a Reply