Skip to content

Instantly share code, notes, and snippets.

@cornernote
Created October 2, 2012 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cornernote/3818812 to your computer and use it in GitHub Desktop.
Save cornernote/3818812 to your computer and use it in GitHub Desktop.
pairs, ipairs and #tablename iteration
--[[
Tables in Lua may contain both ordered (numbered) and unordered (named) members. Most of the time, you'll use just named elements, or just numbered elements, but there are surprisingly frequent occasions when it's useful to use both. You then need to remember if you iterate through members that ...
- #tablename will only go through numbered elements, and will give you nil if there's a gap in the numbering
- pairs will take you through all elements with non-nil values, but won't give you any members which are explicitly or implicitly set to nil
- ipairs will start at the element numbered 1, and go up through numbered elements until it reaches a nil, at which point it will go no further.
source: http://www.wellho.net/resources/ex.php4?item=u105/ph
]]--
print ("Set up a table, indexed, with a hole")
vals = {"one","two","three",nil,"five"}
print ("Iterate through it using #tablename")
for k=1,#vals do
print (k,vals[k])
end
print ("Add a numbered value after a gap. Works fine")
vals[8] = "eight"
for k=1,#vals do
print (k,vals[k])
end
print ("Add a named value - but not seen by the loop")
vals["nine"] = "It's 9"
for k=1,#vals do
print (k,vals[k])
end
print ("Pairs goes through all the elements with values")
for k,v in pairs(vals) do
print (k,v)
end
print ("Ipairs starts at element 1, goes up 1 at a time and stops when it finds a nil")
for k,v in ipairs(vals) do
print (k,v)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment