Is there an efficient and elegant way to truncate a number like this in Lua?

What i want to do

What I want to do is very simple. I want to use Lua to check the lines in a Plist file.

Say if the string is in Plist,, <integer>-1.00</integer>I need to cut .00it so that it is <integer>-1</integer>.

What I've done

I use the function to read the entire contents of the file and perform a line check and replace.

local function doLineClean( cont )
    newcont = ''
    string.gsub( cont, "(.-)\r?\n", function(line)
        if string.match( line, "<integer>.-<%/integer>" ) then
            string.gsub( line, "<.->(.-)<.->", function(v)
            a, b = string.find(v,"%..*")
            if a and b then
                v = string.sub( v, 0, a - 1 )
            end
            line = "\t\t<integer>"..v.."</integer>"
            end  )
        end
        newcont = newcont .. line .. '\n'
    end  )
    return newcont
end

My question

Is there a more efficient and elegant way to do the same job?

+4
source share
2 answers

First, note that Lua string patterns are not full regular expressions. They are more limited and less powerful, but usually sufficient (as in this case).

, , ?

local s1 = [[
<integer>3</integer>
<integer>3.12</integer>
<integer>-1.00</integer>
<integer>-1.99</integer>
<float>3.14</float>
]]

local s2 = s1:gsub('(<integer>%-?%d+)%.%d+','%1')
print(s2)
--> <integer>3</integer>
--> <integer>3</integer>
--> <integer>-1</integer>
--> <integer>-1</integer>
--> <float>3.14</float>

:

  • <integer>,
  • (%-?)
  • (%d+)
  • (%.)
  • (%d+)

( 1-3, ).

, , (, <integer>.99</integer>) (, <integer>1.34e7</integer>).

+7

:

s = "<integer>-1.00</integer>"
s:gsub("[.]%d*","")
-2

All Articles