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

Question:
Lua has which control structures?

Lua has these control structures:
  • if
  • repeat
  • while
  • for
dan@hp ~/ks/b/lua $ 
dan@hp ~/ks/b/lua $ 
dan@hp ~/ks/b/lua $ cat control.lua
-- control.lua

a = 1
if a == 1 then
  print('a is 1')
else
  print('a is not 1')
end

n = 4
repeat
  print(n)
  n = n - 1
until n < 1

n = 4
while n > 0 do
  print(n)
  n = n - 1
end

-- Generally, I can use pairs():
for x,y in pairs({k1 = 1.1, k2 = 2.2, k3 = 3.3}) do
  print(x)
end

-- If the keys are integers, I can use ipairs():
for x,y in ipairs({1.1, 2.2, 3.3}) do
  print(x)
end

for x,y in ipairs({1.1, 2.2, 3.3}) do
  print(y)
end

-- Like JavaScript?
for cntr=1, 10, 2 do
  print(cntr)
end

print('cntr is ')
print(cntr) -- should be nil
print('outside the for-loop')
dan@hp ~/ks/b/lua $ 
dan@hp ~/ks/b/lua $ 
dan@hp ~/ks/b/lua $ lua control.lua
a is 1
4
3
2
1
4
3
2
1
k3
k2
k1
1
2
3
1.1
2.2
3.3
1
3
5
7
9
cntr is 
nil
outside the for-loop
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