home ~ projects ~ socials

Get The Number Of Items In A Lua Table

This is from a 2010 answer. TODO is look up to see if there's a different way now

local function table_length(source)
  local count = 0
  for _ in pairs(source) do 
    count = count + 1 
  end
  return count
end


local example = { 
  alfa = "apple", 
  bravo = "bean", 
  charlie = "cherry"
}

print(table_length(example))
Output:
3
-- end of line --

References