Lua中對table排序?qū)嵗?/h1>
更新時間:2014年09月27日 15:46:31 作者:Mr.Ant
這篇文章主要介紹了Lua中對table排序?qū)嵗?本文講解了Lua中對table的一般排序方法、針對值的排序、同時對鍵值進行排序等方法,需要的朋友可以參考下
lua中利用到的排序的基本上就是構(gòu)造函數(shù)(table)了,為了便于和C區(qū)分開來,我俗稱它為表單。
實例:(原理就是LUA集成的冒泡算法)
排序的一般姿勢(對于只包含數(shù)字或者只包含字符串的簡單數(shù)組)
復(fù)制代碼 代碼如下:
table.sort(test)
擴展版
復(fù)制代碼 代碼如下:
table.sort(test, function(a,b) return a.id<b.id end )
實例一:值排序
1.數(shù)組模式
復(fù)制代碼 代碼如下:
local test0 ={1,9,2,8,3,7,4,6}
table.sort(test0) --從小到大排序
for i,v in pairs(test0) do
io.write(v.." ")
end
print("");
table.sort(test0,function(a,b) return a>b end) --從大到小排序
for i,v in pairs(test0) do
io.write(v.." ")
end
print(" ")
2.表單模式
復(fù)制代碼 代碼如下:
local test2 ={
{id=1, name="deng"},
{id=9, name="luo"},
{id=2, name="yang"},
{id=8, name="ma"},
{id=5, name="wu"},
}
table.sort(test2,function(a,b) return a.id<b.id end )
for i in pairs(test2) do
print(test2[i].id,test2[i].name)
end
實例二:鍵值排序
復(fù)制代碼 代碼如下:
local test1 ={a=1,f=9,d=2,c=8,b=5}
local key_test ={}
for i in pairs(test1) do
table.insert(key_test,i) --提取test1中的鍵值插入到key_test表中
end
table.sort(key_test)
for i,v in pairs(key_test) do
print(v,test1[v])
end
相關(guān)文章
-
Lua獲取系統(tǒng)時間和時間格式化方法及格式化參數(shù)
這篇文章主要介紹了Lua獲取系統(tǒng)時間和時間格式化方法及格式化參數(shù),需要的朋友可以參考下 2015-04-04
lua中利用到的排序的基本上就是構(gòu)造函數(shù)(table)了,為了便于和C區(qū)分開來,我俗稱它為表單。
實例:(原理就是LUA集成的冒泡算法)
排序的一般姿勢(對于只包含數(shù)字或者只包含字符串的簡單數(shù)組)
table.sort(test)
擴展版
table.sort(test, function(a,b) return a.id<b.id end )
實例一:值排序
1.數(shù)組模式
local test0 ={1,9,2,8,3,7,4,6}
table.sort(test0) --從小到大排序
for i,v in pairs(test0) do
io.write(v.." ")
end
print("");
table.sort(test0,function(a,b) return a>b end) --從大到小排序
for i,v in pairs(test0) do
io.write(v.." ")
end
print(" ")
2.表單模式
local test2 ={
{id=1, name="deng"},
{id=9, name="luo"},
{id=2, name="yang"},
{id=8, name="ma"},
{id=5, name="wu"},
}
table.sort(test2,function(a,b) return a.id<b.id end )
for i in pairs(test2) do
print(test2[i].id,test2[i].name)
end
實例二:鍵值排序
local test1 ={a=1,f=9,d=2,c=8,b=5}
local key_test ={}
for i in pairs(test1) do
table.insert(key_test,i) --提取test1中的鍵值插入到key_test表中
end
table.sort(key_test)
for i,v in pairs(key_test) do
print(v,test1[v])
end
相關(guān)文章
Lua獲取系統(tǒng)時間和時間格式化方法及格式化參數(shù)
這篇文章主要介紹了Lua獲取系統(tǒng)時間和時間格式化方法及格式化參數(shù),需要的朋友可以參考下2015-04-04

Mac平臺中編譯安裝Lua運行環(huán)境及Hello Lua實例