lua - cheatsheet

Almost everything is ripped from here: https://zserge.wordpress.com/2012/02/23/lua-%D0%B7%D0%B0-60-%D0%BC%D0%B8%D0%BD%D1%83%D1%82/

Comment — ‘–’

Parentheses and ‘;’ are optional:

-- my first lua app: hello.lua
print "hello world";
print("goodbye world")

Conditions, loops

if/then/elseif/else/end

case — none

for i = 1, 10, 2 do … end

while a == ‘’ do … end

repeat … until a == ‘’

Expressions

  • assignment: x = 0
  • arithmetic: +, -, *, /, % (remainder of division), ^ (exponentiation)
  • logical: and, or, not
  • comparison: >, <, ==, <=, >=, ~= (not-equal)
  • string concatenation (the “..” operator)
  • length/size (the “#” operator): s=”hello”; a = #s (a will equal 5).
  • getting an element by index, e.g.: s[2]

Types

  • nil
  • boolean (true/false)
  • numbers — with no split into integer/real. Just numbers.
  • strings
  • functions
  • thread
  • arbitrary data (userdata)
  • table = hash/array/struct/class

a[‘test’] ~ a.test

creating a table:

t = {
  a = 3,
  b = 4
}
for key, value in pairs(t) do
  print(key, value) -- prints "a 3", then "b 4"
end

Iteration:

u={}; u[1]="a"; u["x"]="z"
-- Numeric keys only!!! But in the correct order
for key,value in ipairs(u) do print(key,value) end
-- 1   a
-- All keys, but in random order
for key,value in pairs(u) do print(key,value) end
-- 1   a
-- x   z

The size of a table can only be obtained by explicitly iterating over all elements and counting them. #name does not work!

Functions

function add(a, b)
  return a + b
end

You can return several values.

A variable number of arguments:

function sum(...) 
   s = 0
   for _, n in pairs(arg) do -- inside the function they are accessed as the "arg" table
      s = s + n
   end
   return a
end

Objects

lamp = { on = false turn_on = function(l) l.on = true end }

lamp.turn_on(lamp) lamp:turn_on() lamp[‘turn_on’](lamp) – all three variants are equivalent

function lamp:turn_off() self.on = false end – add a method on the fly

Special functions

Some table function (method) names are reserved and carry a special meaning:

  • __add(a, b), __sub(a, b), __div(a, b), __mul(a, b), __mod(a, b), __pow(a, b) — called when arithmetic operations are performed on a table
  • __unm(a) — the unary “minus” operation (when you write something like “x = -x”)
  • __lt(a, b), __le(a, b), __eq(a, b) — compute the result of a comparison (<, <=, ==)
  • __len(a) — called when you do “#a”
  • __concat(a, b) — called on “a..b”
  • __call(a, …) — called on “a()”. The variadic arguments are the call’s arguments
  • __index(a, i) — access to a[i] when no such element exists
  • __newindex(a, i, v) — creation of “a[i] = v”
  • __gc(a) — when the object is removed during garbage collection

By overriding these methods you can overload operators and use the language syntax for your own purposes.

Inheritance

There is no real inheritance, since there are no classes. But you can pull in methods from another object:

superlamp = {
  brightness = 100
}
-- specify the parent table
setmetatable(superlamp, lamp)
-- and its methods are now available
superlamp:turn_on()
superlamp:turn_off()

System calls

Popen:

local handle = io.popen(command)
local result = handle:read("*a")
handle:close()

Reading/writing a file:

-- Opens a file in read
file = io.open("test.lua", "r")  -- r,w,a,r+,w+,a+   + - create in not exists
-- sets the default input file as test.lua
io.input(file)
-- prints the first line of the file
print(io.read())
-- closes the open file
io.close(file)

-- Opens a file in append mode
file = io.open("test.lua", "a")
-- sets the default output file as test.lua
io.output(file)
-- appends a word test to the last line of the file
io.write("-- End of the test.lua file")
-- closes the open file
io.close(file)

Reading the lines of a file:

-- see if the file exists
function file_exists(file)
  local f = io.open(file, "rb")
  if f then f:close() end
  return f ~= nil
end

-- get all lines from a file, returns an empty 
-- list/table if the file does not exist
function lines_from(file)
  if not file_exists(file) then return {} end
  local lines = {}
  for line in io.lines(file) do 
    lines[#lines + 1] = line
  end
  return lines
end