Sorting in Lua (beginners question)

Hi,

I’m a Silverbullet beginner with no lua experience, trying to create an lua script that will give me a list of the most common tags, but I can’t get the sort function to work.

The function I wrote so far is below (I haven’t done the formatting of the output yet). However, the sort function does not seem to change the order at all and it doesn’t seem to give an error either.

function countTags()
  -- Count tags
  local pageTags = {}
  for tag in query[[from index.tag 'tag']] do
    if not pageTags[tag.name] then
      pageTags[tag.name] = 1
    else
      pageTags[tag.name] = pageTags[tag.name] + 1
    end
  end

  table.sort(pageTags, function(a, b) return a.value < b.value end)
  return pageTags

This doesn’t sort the table at all.

I’ve tried to sort only the values in the table, which kind of works, but it sorts them as strings (so 11 comes before 2)

  local v = {}
  for tag, count in pairs(pageTags) do
    table.insert(v, count)
  end
  
  table.sort(v)
  return v

Appreciate if you can give me some pointers on how I can get my table sorted numerically.

Tnx,

Mike

Nevermind, I solved it with a little help from AI:

function countTags(returnAmount)
  -- Aggregate tasks per page
  local pageTags = {}
  for tag in query[[from index.tag 'tag']] do
    if not (tag.name:lower() == "meta" or tag.name:lower():find("^meta/")) then
      if not pageTags[tag.name] then
        pageTags[tag.name] = 1
      else
        pageTags[tag.name] = pageTags[tag.name] + 1
      end
    end
  end

  -- Convert the dictionary to a list of {key, value} tables
  local sortedTags = {}
  for k, v in pairs(pageTags) do
    table.insert(sortedTags, {name = '#' .. k, value = v})
  end

  -- Sort the list by value
  table.sort(sortedTags, function(a, b) return a.value > b.value end)
  
  -- Return only the top results
  local topResult = {}
  for i = 1, math.min(returnAmount, #sortedTags) do
    table.insert(topResult, sortedTags[i])
  end

  return topResult

end