syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me

Question:
In Lua why use do-end?

Sometimes when I work with other peoples code I worry about using a variable name which might clash with another variable name.

Often I tempted to create variables with names like 'name' or 'state'.

If I create a variable named 'state', I might create a bug in the code because another developer already created the 'state' variable and the code is using it.

I can use a local variable inside a do-end block to minimize this problem.

The syntax is simple. Just start the block with 'do' and end it with 'end'.

Inside the block add the 'local' keyword (only once) before my variable:
dan@hp ~/ks/b/lua $ 
dan@hp ~/ks/b/lua $ 
dan@hp ~/ks/b/lua $ cat do_end.lua
-- do_end.lua

state = 'Calif'
name  = 'Dan'
print('state and name are global')
print(state, name)

do
  local state = 'ready'
  local name  = 'computer'
  print('state and name are local')
  print(state, name)
  print('state and name are still local?')
  state = 'notready'
  name  = 'router'
  print(state, name)
  print('yes, state and name are local')
end

print('local state and name now gone')
print('state and name are global')
print(state, name)

dan@hp ~/ks/b/lua $ 
dan@hp ~/ks/b/lua $ 
dan@hp ~/ks/b/lua $ lua do_end.lua
state and name are global
Calif	Dan
state and name are local
ready	computer
state and name are still local?
notready	router
yes, state and name are local
local state and name now gone
state and name are global
Calif	Dan
dan@hp ~/ks/b/lua $ 
dan@hp ~/ks/b/lua $ 
dan@hp ~/ks/b/lua $ 


syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me