在 Lua 中 maxn 函数用于指定 table 中所有正数 key 值中最大的 key 值,如果不存在 key 值为正数的元素, 则返回 0。(Lua 5.2 之后该方法已经不存在了)
table.maxn (table)
参数 | 描述 |
---|---|
table | 要求值的表 |
返回最大值。
使用 maxn() 函数,实现求表的最大值
#!/usr/bin/lua
print("haicoder(www.haicoder.net)\n")
function table_maxn(t)
local mn=nil;
for k, v in pairs(t) do
if(mn==nil) then
mn=v
end
if mn < v then
mn = v
end
end
return mn
end
tbl = {[1] = 2, [2] = 6, [3] = 34, [26] =5}
print(string.format("max = %d", table_maxn(tbl)))
程序运行后,控制台输出如下:
我们使用了 table.maxn 实现了在表中最大值元素。
在 Lua 中 maxn 函数用于指定 table 中所有正数 key 值中最大的 key 值,如果不存在 key 值为正数的元素, 则返回 0。(Lua5.2 之后该方法已经不存在了)