Linked lists are your friend for something like this.
In case you don't know what these are you add a field to each entry called next, this indicates the next entry in the list. You can have multiple nexts, eg nextName, nextAddress, as well as prevName etc if you want. Then when it comes to printing it out, you can do so in order without having done any actual sorting.
An example implementation:
local llist={}
llist[1]={nextName=2,nextSurname=2}
local function addToList(entry)
llist[#llist+1]=entry
local thisName=1
local thisSurname=1
local nextNameEntry=llist[1].nextName
local nextSurnameEntry=llist[1].nextSurname
while llist[#llist].nextName==nil and llist[#llist].nextSurname==nil do
if nextNameEntry>0 and (llist[nextNameEntry]=nil or llist[nextNameEntry].name>entry.name) then
llist[#llist].nextName=llist[thisName].nextName
llist[thisName].nextName=#llist
nextNameEntry=-1
elseif nextNameEntry>0 then
nextNameEntry=llist[thisName].nextName
end
if nextSurnameEntry>0 and (llist[nextSurnameEntry]=nil or llist[nextSurnameEntry].surname>entry.surname) then
llist[#llist].nextSurname=llist[thisSurname].nextSurname
llist[thisSurname].nextSurname=#llist
nextSurnameEntry=-1
elseif nextSurnameEntry>0 then
nextSurnameEntry=llist[thisSurname].nextSurname
end
end
end
local function listByName()
nextName=llist[1].nextName
while nextName~=nil do
print(llist[nextName].name.." "..llist[nextName].surname)
nextName=llist[nextName].nextName
end
end
local function listBySurname()
nextSurname=llist[1].nextSurname
while nextSurname~=nil do
print(llist[nextSurname].surname..", "..llist[nextSurname].name)
nextSurname=llist[nextSurname].nextSurname
end
end
I'm pretty sure I've cocked up the implementation of addToList, but it shows you the general shape of how it works. Removing entries basically involves looping through the list and counting your position until your position gets to the entry you want to delete, then just link the previous entry to the next entry and it will vanish from the list (don't forget to set that entry to nil, but don't use table.remove as that will break everything)
They are a very powerful tool and well worth looking into