我收到以下字符串数据作为输入:
"route1,1234,1,no~,,route2,1234,1,no~,"
它代表两个“记录”的数据......其中每条记录有 4 个字段。我已经构建了代码来将此字符串解析为单独的列/字段。但不起作用的部分是当我测试字段 2 中是否有任何重复项时。字段 2 是当前具有“1234”作为值的字段。
这是代码:
function string:split(delimiter)
local result = { }
local from = 1
local delim_from, delim_to = string.find( self, delimiter, from )
while delim_from do
table.insert( result, string.sub( self, from , delim_from-1 ) )
from = delim_to + 1
delim_from, delim_to = string.find( self, delimiter, from )
end
table.insert( result, string.sub( self, from ) )
return result
end
local check_for_duplicate_entries = function(route_data)
local route
local route_detail = {}
local result =true
local errtxt
local duplicate = false
print("received :" ..route_data)
route = string.gsub(route_data, "~,,", "~")
route = route:sub(1,string.len(route)-2)
print("route :" ..route)
-- break up in to an array
route = string.split(route,"~")
for key, value in pairs(route) do
route_detail[key] = string.split(value,",")
end
local list_of_second_column_only = {}
for key,value in pairs(route_detail) do
local temp = value[2]
print(temp .. " - is the value I'm checking for")
if list_of_second_column_only[temp] == nil then
print("i dont think it exists")
list_of_second_column_only[key] = value[2]
print(list_of_second_column_only[key])
else
--found a duplicate.
return true
end
end
return false
end
print(check_for_duplicate_entries("route1,1234,1,no~,,route2,1234,1,no~,"))
我认为我要去错的地方是测试:
if list_of_second_column_only[temp] == nil then
我想我正在检查带有值 temp 的键,而不是带有 temp 包含的值的值。但我不知道如何修复语法。另外,我想知道是否有更有效的方法来做到这一点。我作为输入接收的“记录”数量是动态/未知的,每条记录中第二列的值也是如此。
谢谢。
编辑 1
我试图用作参考的帖子是:Search for an item in a Lua list
在答案中,他们展示了如何按值测试表中的记录,而不是遍历整个表......
if items["orange"] then
-- do something
end
我正在玩耍试图做类似的事情......