如何在Lua脚本中查询并打印指定用户的最近5条购买记录
修改Lua脚本实现用户最近5条购买记录查询
原功能与需求说明
- 原脚本功能:用户完成购买时,
CheckList()会将购买信息(BuyerName、LatestPurchases、DateTime)插入JobList_Table(插入到表头,确保最新记录排在最前);原ShowList()仅能查询指定用户的最后1条购买记录。 - 修改需求:调整
ShowList(),使其显示指定用户的最近最多5条购买记录(购买次数不足5条则显示全部),逻辑等价于SQL语句:
SELECT TOP 5 BuyerName,LatestPurchases,DateTime from JobList_Table where BuyerName = "Marie" ORDER BY IndexID DESC
原Lua脚本
JobList_Table = {} function CheckList() --> Called whenever someone makes a purchase. table.insert(JobList_Table,1, { ["BuyerName"] = "Marie", -->Simulating with the name Marie - In the original script this name is added by a function. ["LatestPurchases"] = "Potatoes", -->Simulating with Potato ["DateTime"] = os.time() } ) --[[ ->for simulate in print,keep the JobList_Table,1,because that's how the program inserts table.insert(JobList_Table,1, { ["BuyerName"] = "Marie", ["LatestPurchases"] = "Strawberries", ["DateTime"] = os.time() } ) table.insert(JobList_Table,1, { ["BuyerName"] = "Emma", ["LatestPurchases"] = "Chayote", ["DateTime"] = os.time() } )--]] end function ShowList() -->Executed for verification. local NewUser = 1 local ExecutionName = "Marie" if NewUser ~= 0 then for Index,Data in ipairs(JobList_Table) do if Data.BuyerName ~= nil and Data.BuyerName == ExecutionName then print(Data.BuyerName, Data.LatestPurchases, Data.DateTime) --LOGS SHOW return end end print("Dont Find Or Nil") return end print("Is Not New User") end
修改后的Lua脚本
JobList_Table = {} function CheckList() --> Called whenever someone makes a purchase. table.insert(JobList_Table,1, { ["BuyerName"] = "Marie", -->Simulating with the name Marie - In the original script this name is added by a function. ["LatestPurchases"] = "Potatoes", -->Simulating with Potato ["DateTime"] = os.time() } ) --[[ ->for simulate in print,keep the JobList_Table,1,because that's how the program inserts table.insert(JobList_Table,1, { ["BuyerName"] = "Marie", ["LatestPurchases"] = "Strawberries", ["DateTime"] = os.time() } ) table.insert(JobList_Table,1, { ["BuyerName"] = "Emma", ["LatestPurchases"] = "Chayote", ["DateTime"] = os.time() } )--]] end function ShowList() -->Executed for verification. local NewUser = 1 local ExecutionName = "Marie" -- 新增计数器,控制最多显示5条记录 local recordCount = 0 if NewUser ~= 0 then for Index,Data in ipairs(JobList_Table) do -- 找到匹配用户的记录 if Data.BuyerName ~= nil and Data.BuyerName == ExecutionName then print(Data.BuyerName, Data.LatestPurchases, Data.DateTime) --LOGS SHOW recordCount = recordCount + 1 -- 达到5条就停止遍历 if recordCount >= 5 then break end end end -- 若一条匹配记录都没找到,打印提示 if recordCount == 0 then print("Dont Find Or Nil") end return end print("Is Not New User") end
修改关键点说明
- 移除了原脚本中找到第一条匹配记录就立即
return的逻辑,改为计数收集; - 添加
recordCount计数器,每找到一条匹配记录就递增,达到5条时终止遍历; - 遍历结束后判断计数器是否为0,若为0则打印未找到的提示信息;
- 保持原有的表头插入逻辑,确保最新记录优先被遍历到,符合“最近购买”的排序需求。
内容的提问来源于stack exchange,提问作者larissabr
相关产品推荐
相关产品推荐

