首先来个简单的例子
local test_table = {2,1,3} table.sort(test_table) for key,value in pairs(test_table) do print(key,value) end
>lua -e "io.stdout:setvbuf 'no'" "test.lua" 1 1 2 2 3 3
local test_table = {"a","c","b"} table.sort(test_table) for key,value in pairs(test_table) do print(key,value) end
>lua -e "io.stdout:setvbuf 'no'" "test.lua" 1 a 2 b 3 c
local test_table = {"a",1,"c",3,"b",2} table.sort(test_table) for key,value in pairs(test_table) do print(key,value) end
>lua -e "io.stdout:setvbuf 'no'" "test.lua" lua: attempt to compare number with string stack traceback: [C]: in function 'sort' test.lua:2: in main chunk [C]: ?
local test_table = {2,b = 12,c = 34,a = 56,1,d= 78,4,3} table.sort(test_table) for key,value in pairs(test_table) do print(key,value) end
>lua -e "io.stdout:setvbuf 'no'" "test.lua" 1 1 2 2 3 3 4 4 a 56 d 78 c 34 b 12
local test_table = {a=3,b=2,c=4,d=1} table.sort(test_table) for key,value in pairs(test_table) do print(key,value) end
>lua -e "io.stdout:setvbuf 'no'" "test.lua" a 3 d 1 c 4 b 2
local test_table = {a=3,b=2,c=4,d=1} local key_table = {} --取出所有的键 for key,_ in pairs(test_table) do table.insert(key_table,key) end --对所有键进行排序 table.sort(key_table) for _,key in pairs(key_table) do print(key,test_table[key]) end
>lua -e "io.stdout:setvbuf 'no'" "test.lua" a 3 b 2 c 4 d 1