你如何在Lua中解析这个字符串 "1 2 3 4"?

我来自纯 VB.Net 背景的 Lua 新手。我有一个需要迭代的大型地图线路文件。数据格式如下:

;XX.XXX YY.YYY 名称 ; [空中航线] 58.50 -12.44 58.21 -13.73 58.21 -13.73 57.89 -15.02 57.89 -15.02 57.54 -16.30 57.54 -16.30 57.17 -17.58 57.17 -17.58 56.76 -18.84 56.76 -18.84 56.33 -20.10 56.33 -20.10 55.87 -21.35 54.33 -25.02 53.77 -26.22

我尝试了这个代码,但一直出现错误。

local mapLines = {}

local filePath = system.pathForFile( "data.ini", system.DocumentsDirectory )

local file = io.open( filePath, "r" )

if file then
    local contents = file:read( "*a" )

    --print( "Contents of " .. filePath )
    --print( contents )

    io.close( file )

    local t = display.newText( "Contents of ", 5, 80, nil, 16 );
    t:setTextColor( 255, 255, 136, 255 );
    local t = display.newText( filePath, 5, 100, nil, 10 );
    t:setTextColor( 255, 255, 136, 255 );

    local ylast = 130
    for line in io.lines(filePath) do
        local t = display.newText( line, 15, ylast, nil, 14 );
        t:setTextColor( 255, 255, 255 );
        ylast = ylast + 20

        n = tonumber(line);
        if n == nil then

            local f = {}
            s = "1 2 3 4"
            for k, v in string.gmatch(s, "(%w+) (%w+)") do
            f[k] = v
            end

            local myLine = newLine(tonumber(f[1]), tonumber(f[2]), tonumber(f[3]), tonumber(f[4]))
            table.insert( mapLines, myLine )
        end
    end
end

-- 绘制图形函数示例

local function newLine(x,y,x1,y1)

    -- 需要初始线段开始
    local Line = display.newLine( x, y, x1, y1 )

    Line:setColor( 30, 155, 30, 100 )
    Line.width = 3

    return Line
end

Runtime:addEventListener( "enterFrame", mapLines )

任何帮助将不胜感激!

Dave

原文链接 https://stackoverflow.com/questions/4729226

点赞
stackoverflow用户459706
stackoverflow用户459706

回答主题问题:

这段代码的作用是将字符串中的每个数字取出来并打印出来。使用了 Lua 的函数 gmatch,配合正则表达式的模式 %d+,表示匹配至少一个数字,循环遍历字符串中的每个数字并打印出来。

local string_to_parse = '1 2 3 4'

for s in string_to_parse:gmatch('%d+') do
   print(s)
end

codepad 上有该代码的示例。

2011-01-19 10:11:18