Lua Memo

テーブルを並び替える

table.sort (table [, comp])

table[1] から table[n] までのテーブル要素を、指定された順序で その場でソートする。 ソート関数 comp を与えることができる。comp が与えられなければ、標準のLuaの演算子 < が代わりに使われる。

sample

普通にソートする場合

t = {5,3,1,2,4,6}
table.sort(t)
print(table.concat(t,":")) --> 1:2:3:4:5:6

比較関数を入れる場合

t = {
	{name="sabu", age=17},
	{name="jiro", age=20},
	{name="siro", age=13},
	{name="taro", age=30}
}
table.sort(t,
	function(a,b)
		return (a.age < b.age)
	end)
for index, value in pairs(t) do
	print(value.name..":"..value.age)
end
--[[
siro:13
sabu:17
jiro:20
taro:30
--]]

link