0 Replies - 304 Views - Last Post: 09 April 2009 - 06:19 AM

#1 KYA   User is offline

  • Wubba lubba dub dub!
  • member icon

Reputation: 3202
  • View blog
  • Posts: 19,233
  • Joined: 14-September 07

[LUA]Lua: FindMax Value in a Table

Posted 09 April 2009 - 06:19 AM

Description: Implement in a sort program of some nature? Iterates through data to find the largest number. also illustrates returning multiple values from a function. Returns max number and its index location.
--KYA 4/9/09
--Functions fins the max value in a table
--Also illustrates multiple returns in a function
function findMax(a)
	local mi = 1			--index of max value
	local m = a[mi]			--max value
	for i, val in ipairs(a) do      --can use pairs() as well, ipairs() indicates an array-like table
		if val > m then
			mi = i
			m = val
		end
	end
	return m, mi	--neat feature of lua, can return multiple values
end


--example usage
print(findMax({2,6,90,45,67,88,100}))	-->100 7, max num and index location


Is This A Good Question/Topic? 0
  • +

Page 1 of 1