为了账号安全,请及时绑定邮箱和手机立即绑定

lua中对数组排序的问题

lua中对数组排序的问题

茅侃侃 2019-04-11 06:06:53
function order(x)maxn = table.getn(x)for j=1,maxn ,1 dofor i = j,maxn,1 doif x[j].no < x[i].no thenx[j],x[i] = x[i],x[j]endendendreturn xend以上是以数组的.no项来进行排序的现在我想把函数调整为orderby(x,y)其中y代表的是数组中的排序的列名,应该咋实现啊?
查看完整描述

3 回答

?
红颜莎娜

TA贡献1842条经验 获得超12个赞

.no的含义和["no"]是一样的。所以改成下面这样
function orderby(x,y)--x是数组,y是列名用字符串,比如"no"
maxn = table.getn(x)
for j=1,maxn ,1 do
for i = j,maxn,1 do
if x[j][y] < x[i][y] then
x[j],x[i] = x[i],x[j]
end
end
end
return x
end

查看完整回答
反对 回复 2019-04-12
?
萧十郎

TA贡献1815条经验 获得超12个赞

比如数组x={{a=1,b="n",c=true},{a=2,b="f",c=true}}
怎么能取到abc这3个列名?
for _,sub in pairs(x) do
for k,v in pairs(sub) do
  print(k)--k是字符串 ”a“,”b“,”c“
end
end

查看完整回答
反对 回复 2019-04-12
  • 3 回答
  • 0 关注
  • 1506 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信