table常用工具函数 - list用法
table_listext.lua
function list.reset(listTb, val) for i=1,#listTb do listTb[i] = val end end function list.castItemToNum(listTb) for i=1,#listTb do listTb[i] = tonumber(listTb[i]) end return listTb end function list.castItemToString(listTb) for i=1,#listTb do listTb[i] = tostring(listTb[i]) end return listTb end function list.reverse(listTb) local len = #listTb local half = math.floor(len * 0.5) for i=1,half do table.swap(listTb, i, len - i + 1) end end
添加
function list.appendList(listTb, srcListTb) for i=1,#srcListTb do table.insert(listTb, srcListTb[i]) end return listTb end function list.appendTable(listTb, tb) for k, v in pairs(tb) do table.insert(listTb, v) end return listTb end
查找
--从前往后找 function list.indexOfItem(listTb, item) for i=1,#listTb do if listTb[i] == item then return i end end return -1 end ---从后往前找 function list.lastIndexOfItem(listTb, item) for i=#listTb,1,-1 do if listTb[i] == item then return i end end return -1 end
查找匹配
---从前往后找匹配 function list.indexOfMatch(listTb, matchFunc) for i=1,#listTb do local item = listTb[i] if matchFunc(i, item) then return i end end return -1 end ---从后往前找匹配 function list.lastIndexOfMatch(listTb, matchFunc) for i=#listTb,1,-1 do local item = listTb[i] if matchFunc(i, item) then return i end end return -1 end
删除
---从前往后, 删除第1个相等的 function list.removeFirstItem(listTb, item) for i=1,#listTb do if listTb[i] == item then table.remove(listTb, i) return i end end return -1 end ---从后往前, 删除反向第1个相等的 function list.removeLastItem(listTb, item) for i=#listTb,1,-1 do if listTb[i] == item then table.remove(listTb, i) return i end end end ---删除所有相等的 function list.removeAllItems(listTb, item) local count = 0 for i=#listTb,1,-1 do if listTb[i] == item then table.remove(listTb, i) count = count + 1 end end return count end
删除匹配
---从前往后, 删除第1个匹配的 function list.removeFirstMatch(listTb, matchFunc) for i=1,#listTb do local item = listTb[i] if matchFunc(i, item) then table.remove(listTb, i) return i, item end end return -1 end ---从后往前, 删除反向第1个匹配的 function list.removeLastMatch(listTb, matchFunc) for i=#listTb,1,-1 do local item = listTb[i] if matchFunc(i, item) then table.remove(listTb, i) return i, item end end end ---删除所有匹配的 function list.removeAllMatch(listTb, matchFunc) local count = 0 for i=#listTb,1,-1 do local item = listTb[i] if matchFunc(i, item) then table.remove(listTb, i) count = count + 1 end end return count end
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端