lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I'm new to the list and have just written my first Lua program (see below).
My question is I am sorting a list with different types, and I
have a solution that works below, but I am sure there is a much better
way. Can anyone offer a neater solution please? The main problem
is getting the compare neat, as you have to compare a number to
a string when sorting the list.


-- globals
true = 0
false = -1
length = 0

-- print_item and count items in list
function print_item(i,x)
	print (i,x)
	length = length + 1 -- I don;t like doing this

-- check_item
function check_item (a,b)
	a = strlower(a)
	b = strlower(b)
	a = tostring (a)
	b = tostring (b)
	return a, b

-- sort_list
function sort_list (list,n)
	local sorted = true
	while sorted == true do
		sorted = false
		for i=1,n-1,1 do
			a, b = check_item (list[i],list[i+1])
			if a>b then
				list[i],list[i+1] = list[i+1],list[i] -- swap
				sorted = true

-- list = {3,7,4,2.1,3.1416,9,-1,0}
-- list = {"cat","dog","bird","shark","bat","mouse"}
local list = {"cat",7,"ant",4,2,"bird","Bat","Duck"}

foreachi (list, print_item)
sort_list (list,length)
print ("Sorted list:")
foreachi (list, print_item)


The contents of this e-mail and any attachments are confidential and may
be legally privileged. If you have received this e-mail and you are not
a named addressee, please inform us as soon as possible on
+44 118 901 2999 and then delete the e-mail from your system. If you are
not a named addressee you must not copy, use, disclose, distribute,
print or rely on this e-mail. Any views expressed in this e-mail or any
attachments may not necessarily reflect those of Tao's management.
Although we routinely screen for viruses, addressees should scan this
e-mail and any attachments for viruses. Tao makes no representation or
warranty as to the absence of viruses in this e-mail or any attachments.
Please note that for the protection of our business, we may monitor and
read e-mails sent to and from our server(s).

Visit our website at