PtokaX forum

Development Section => HOW-TO's => Topic started by: plop on 07 June, 2004, 16:22:25

Title: HOW-TO: get a number from a string.
Post by: plop on 07 June, 2004, 16:22:25
made this 1 for the fun, but it's actualy a nice example how to grab a number from a string in multiple way's.
string = "  12.4 GB "

-- strfind with magic
s,e,num = strfind(string, "([%d%.]+)")
print(num)

-- strfind with simple pattern
s,e,num = strfind(string, "(%d+%.%d)")
print(num)

-- strsub
num = strsub(string, 3, (strlen(string)-3) )
print(num)

-- strfind + strsub
a,b = strfind(string, "^%D+(%d)")
c,d = strfind(string, "(%d)%D+$")
num = strsub(string,b,c)
print(num)

-- gsub
num = gsub(string, "[^%d%.]","")
print(num)

-- complex gsub
function replace(t)
   if tonumber(t) then
      return t
   elseif t == "." then
      return t
   else
      return ""
   end
end
num = gsub(string, "(.)",function(t) return replace(t) end)
print(num)
if you know more way's pls post them.

plop
Title:
Post by: NotRabidWombat on 08 June, 2004, 22:12:22
Good job.

-NotRabidWombat
Title:
Post by: Herodes on 08 June, 2004, 23:37:45
Very good stuff ..
I think it can be usefull to have the actual result for each of those .. :)
Title:
Post by: plop on 09 June, 2004, 00:03:12
QuoteOriginally posted by Herodes
Very good stuff ..
I think it can be usefull to have the actual result for each of those .. :)
execute the script with the lua command line.
you'll they all have the exact same result, just some take the long way home. lol

@both, thx for the compliments.

plop