lua中pairs/ipairs, foreach/foreachi, table自定义排序

-- 1. table自定义规则排序示例
guild = {}
table.insert(guild, {name = "Cladhaire", class = "Rogue", level = 70})
table.insert(guild, {name = "Sagart", class = "Prieset", level = 70})
table.insert(guild, {name = "Mallaithe", class = "Warlock", level = 40})

local function sortLevelNameAsc(a, b)	-- 自定义排序方法(先按level升序, 再按name升序)
	if a.level == b.level then
		return a.name < b.name
	else
		return a.level < b.level
	end
end

table.sort(guild, sortLevelNameAsc)
print("1. ----------")
for idx, value in ipairs(guild) do
	print(idx, value.level, value.name)
end

-- 2. foreachi和foreach使用
t1 = {2, 4, 6, language="Lua", version="5", 8, 10, 12, web="hello lua"}
print("\n2.1 ----------")
table.foreachi(t1, function(i, v) print(i, v) end)
print("2.2 ----------")
table.foreach(t1, function(i, v) print(i, v) end)

-- 3. pairs和ipairs区别展示
local function display(tbl, fun)
	for k, v in fun(tbl) do
		print(k, v)
	end
end

tbl = {"alpha", "beta", ["one"] = "uno", ["two"] = "dos"}
print("\n3.1 ----------------")
display(tbl, ipairs)
print("3.2 ----------------")
display(tbl, pairs)

运行结果:

zcm@TIANKU /e/program/lua
$ lua t1.lua
1. ----------
1       40      Mallaithe
2       70      Cladhaire
3       70      Sagart

2.1 ----------
1       2
2       4
3       6
4       8
5       10
6       12
2.2 ----------
1       2
2       4
3       6
4       8
5       10
6       12
web     hello lua
language        Lua
version 5

3.1 ----------------
1       alpha
2       beta
3.2 ----------------
1       alpha
2       beta
one     uno
two     dos


你可能感兴趣的:(Lua)