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

Question:
In Lua how to drive forloop with table?

In Lua it is easy to drive a for-loop with a table:
-- table_for.lua

mytable = {}

mytable[1] = 1.1
mytable[2] = 2.2
mytable[3] = 3.3
mytable[4] = 4.4

for i,line in ipairs(mytable) do
  print(line)
end

for i,line in ipairs(mytable) do
  print(i)
end

-- Above syntax silently fails if I use strings as keys:

yourtable = {}
yourtable['key1']    = 'hello'
yourtable['key7']    = 'hola'
yourtable['imakey2'] = 'bonjour'

for i,line in ipairs(yourtable) do
  print(line)
end

-- So, use pairs() instead of ipairs()

atable = {k1 = 'v1'}
atable['key1']    = 'hello'
atable['key7']    = 'hola'

for k,v in pairs(atable) do
  print(k)
  print(v)
end


Screen-dump:

dan@hp ~/ks/b/lua $ 
dan@hp ~/ks/b/lua $ 
dan@hp ~/ks/b/lua $ lua table_for.lua 
1.1
2.2
3.3
4.4
1
2
3
4
key7
hola
k1
v1
key1
hello
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