News: Welcome back to Bullworth! If you haven't already, you will need to reset your password..


Author Topic: Sorting table (array)  (Read 1377 times)

0 Members and 1 Guest are viewing this topic.

Offline RBS ID

  • Jr. Member
  • **
  • Posts: 67
  • Gender: Male
  • I don't know.
    • View Profile
    • This is website title.
Sorting table (array)
« on: May 01, 2022, 06:28:56 AM »
Sorting 1D array:
Code: [Select]
a={'i', 'o', 'a', 'e', 'u'}
table.sort(a)
for _, v in ipairs(a) do
  print(v)
end

Sorting 2D array:
Code: [Select]
G = {}
for k, v in pairs(_G) do
  G[#G+1] = {tostring(k), tostring(v)}    -- #G  is basically just a new syntax of table.getn(G), this # operator doesn't available in Bully's Lua v5.0.2
end
table.sort(G, function(a, b)
  return a[1] < b[1]
end)
for _, v in ipairs(G) do
  print("Key: " .. v[1] .. "\nValue: " .. v[2] .. "\n")
end

Try the code in this site: lua.org/demo.html