Lua Control Statments having odd behavior

一世执手 提交于 2019-12-14 02:43:15

问题


I'm getting a very unexpected result from what should be basic control statement operations. I have the following, a file being read with this sort of data:

1, 51, one , ab
1, 74, two , ab
0, 74, tree , ab
0, 74, for , ab
0, 74, five , ab

My snip of Lua code that processes it:

if file then
for line in file:lines() do
LineArray = line
CanClaimInfo[LineArray] = {}
lineData = utils.split(line,",")
    if lineData[1] == "0"  then
        lineData[1] = "CAN A"
    elseif lineData[1] == "1" then
        lineData[1] = "CAN B"
    else
        lineData[1] = lineData[1]
    end
CanClaimInfo[LineArray]["CANBus"] = lineData[1]
CanClaimInfo[LineArray]["Address"] = lineData[2]
CanClaimInfo[LineArray]["Name"] = lineData[3]
end

and I get this as an output:

CAN A   74  for
CAN A   74  tree
CAN A   74  five
CAN B   74  two
1       51  one

I don't get how it slips through the elseif lineData[1] == "1" then bit. I checked and there are no lead/trailing white spaces or anything like that. Any ideas?


回答1:


Maybe utf-8 encoding bytes at the beginning of file? Try printing lineData[1] before the "if" tests to see what it is, and print(#lineData[1]) to see how many chars it has. Likely more than 1 char so it ends up in that third branch (else):

lineData = utils.split(line,",")
print(#lineData[1]) -- likely prints 1 for all but first line
if lineData[1] == "0"  then

To find the extra bytes, try print(string.byte(lineData[1], 1, #lineData[1])).




回答2:


Hm, seems like your utils.split function has some problems. I used a function from http://lua-users.org/wiki/SplitJoin and it works quite well with your code:

utils = {
    split = function(str, pat)
       local t = {}  -- NOTE: use {n = 0} in Lua-5.0
       local fpat = "(.-)" .. pat
       local last_end = 1
       local s, e, cap = str:find(fpat, 1)
       while s do
          if s ~= 1 or cap ~= "" then
         table.insert(t,cap)
          end
          last_end = e+1
          s, e, cap = str:find(fpat, last_end)
       end
       if last_end <= #str then
          cap = str:sub(last_end)
          table.insert(t, cap)
       end
       return t
    end
}

Maybe your function converts the 1 to a number (for whatever reason). In Lua, "1" ~= 1!



来源:https://stackoverflow.com/questions/21127135/lua-control-statments-having-odd-behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!