Lua

From XennisWiki
Jump to: navigation, search

Lua is a lightweight multi-paradigm programming language designed primarily for embedded systems and clients. Lua is cross-platform since it is written in ANSI C, and has a relatively simple C API. (Wikipedia)

Basics

Comment

-- comment out

Variables

All variables are global and don't have to be initialized. They are nil (such as null) by default.

x = nil -- default value
-- use variable which not exits
print(z) -- prints: nil

Check if variable exists

if x then -- check x exits
  print("x exits")
end

Concatenate variables

i = "Hello"
v = "World"
print(i .. " lovely " .. v) -- prints: Hello lovely World

More stuff

y = {hello = 10} -- without ""
print(y["hello"]) -- prints: 10
print(y.hello) -- same, prints: 10

If condition

if x == 10 then
  print(x)
elseif x == 1 then
  -- do something
else
 -- do something
end
if "hello" == "hello" then
 -- do something
end

Loop

for loop

for x=1, 10, 2 do -- from 1 to 10, step size 2
  print(x)
end

while loop

while x < 10 do
  print(x)
  x = x + 1  -- x++ do not exits in Lua

Tables (arrays)

-- simple
x = {40, 60, 80}
-- mixed
x = {100, "hello", true}

Working with tables

x = {10,20,50}

print(x[1]) --first index one and not zero

x[3] = 60 -- change number
x[4] = 30 -- add value
x["hello"] = 55

print(x["hello"])

Iterate over tables (ipairs, pairs)

ipairs works only with numbers as indices (not with x["hallo"] for instance)

x = {40, 60, 80}

-- i: index, v: value
for i,v in ipairs(x) do
  print(i .. ": " .. v) -- .. concatenate strings
end

pairs works also, when strings are used as indices (such as x["hello"]). However, the function is not such reliable (order may be changed).

x = {40, 60, 80}
x["hello"] = 55
for i,v in pairs(x) do
 -- do something
end

Functions (methods)

Example function

function printer(name)
  print("Hello World" .. name)
end

-- call function
printer("Tom")
space() -- sending blank / nil

All variables are global, unless they are declared in the function as local.

function space()
  local y = 5 -- local variable
  x = 10
end

print(x) -- returns: nil
space()
print(x) -- returns: 10 (after run method)

More stuff

x = {hello = function()
  print("hello")
end}

x.hello()
function space(a1,a2)
  print(a1)
end

See also

External links