< Tables | UserGuide | Functions >


A block is a sequence of code that is executed if the program enters that block. Blocks are associated either standalone, which means the nothing special is happening if the program enters that block - it just continues the execution and exits the block later:

do  -- enter the block here
  print "hello world"
end -- exit the block

The code above will just print out "hello world" and does nothing else.

Blocks do not always look the same:

function foo () -- starts a block
  -- inside the block
end -- ends a block

if true then -- starts a block 
  -- inside the block
end -- ends the block

if false then -- starts
  -- inside
else -- starts another block
end -- ends the second block

Blocks of code are always code pieces that are executed in certain conditions. The do ... end block is always executed if the program reaches the block. The function block is only executed if the function is called at some point of the application. Conditional blocks are only executed if a certain condition is true (or false). Loops like the for- or while loop will execute a block over and over again until some condition is no longer true.

Blocks can be nested inside other blocks:

  -- first
    -- second 
      -- third

Blocks are organizing your code and can hide local variables. Local variables were mentionend in the variable block and it was said that local variables are only accessible in a certain range of the program. The blocks are the ranges:

  local x = 5
  print (x) -- can access x (which is 5)
    print (x) -- can access x of the block above
    local x = 10 -- create another variable named x
    print (x) -- accesses the variable named x in this
       -- block, means it prints 10
  print (x) -- will access the x of this block - 
    -- the x of the nested block above is no longer 
    -- visible here

print(x) -- won't print anything. x is no longer visible