Any suggestions on how do i sort table accordingly to textbox text?
Currently i have this:
table.sort(pets, function(a,b)
return a.Name == Text end)
It gives: 39: invalid order function for sorting
Any suggestions on how do i sort table accordingly to textbox text?
Currently i have this:
table.sort(pets, function(a,b)
return a.Name == Text end)
It gives: 39: invalid order function for sorting
To properly use table.sort(), the sort function should return consistent results, a boolean, when a is b or b is a. Could you provide some specifics on what kind of table pets
is and how you want them sorted?
For example, the textbox text is cat, the table.sort function should sort table so the pet with name “cat” in the table will become on the top of it
Pets = { {Name = “Dog”} , {Name = “Cat”} , {Name = “Dog”} }
it should become
Pets = { {Name = “Cat”} , {Name = “Dog”} , {Name = “Dog”} }
local function sortPetsByName(searchName: string)
searchName = searchName:lower()
table.sort(pets, function(a, b)
if a.Name:lower():match(searchName) then
return true
elseif b.Name:lower():match(searchName) then
-- return false if B matches the search name so that any matches are not pushed further down the table
return false
end
-- normal alphabetical sort if neither A or B match the searching name
return a.Name < b.Name
end)
end
sortPetsByName("cat")
well, it gives “invalid order function for sorting” error
Did you change how the pets table is formatted?
what do you mean formatted?
print(typeof(pets)) → table
I used the format of the pets table that you supplied, and this works in every case
Full source:
local pets = {
{ Name = "Dog" },
{ Name = "Bear" },
{ Name = "Cat" },
{ Name = "Polar Bear" },
{ Name = "Cat" },
{ Name = "Peacock" }
}
local function sortPetsByName(searchName: string)
searchName = searchName:lower()
table.sort(pets, function(a, b)
if a.Name:lower():match(searchName) then
return true
elseif b.Name:lower():match(searchName) then
-- return false if B matches the search name so that any matches are not pushed further down the table
return false
end
-- normal alphabetical sort if neither A or B match the searching name
return a.Name < b.Name
end)
end
sortPetsByName("cat")
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.