Author Topic: HOW-TO: get a number from a string.  (Read 1887 times)

0 Members and 1 Guest are viewing this topic.

Offline plop

  • Forum God
  • ****
  • Posts: 2 464
  • Karma: +37/-0
HOW-TO: get a number from a string.
« 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.
Code: [Select]
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
http://www.plop.nl lua scripts/howto\'s.
http://www.thegoldenangel.net
http://www.vikingshub.com
http://www.lua.org

>>----> he who fights hatred with hatred, drives the spreading of hatred <----<<

PtokaX forum

HOW-TO: get a number from a string.
« on: 07 June, 2004, 16:22:25 »

Offline NotRabidWombat

  • Lord
  • ***
  • Posts: 384
  • Karma: +2/-0
(No subject)
« Reply #1 on: 08 June, 2004, 22:12:22 »
Good job.

-NotRabidWombat


I like childish behavior. Maybe this post will be deleted next.

Herodes

  • Guest
(No subject)
« Reply #2 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 .. :)

Offline plop

  • Forum God
  • ****
  • Posts: 2 464
  • Karma: +37/-0
(No subject)
« Reply #3 on: 09 June, 2004, 00:03:12 »
Quote
Originally 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
http://www.plop.nl lua scripts/howto\'s.
http://www.thegoldenangel.net
http://www.vikingshub.com
http://www.lua.org

>>----> he who fights hatred with hatred, drives the spreading of hatred <----<<

PtokaX forum

(No subject)
« Reply #3 on: 09 June, 2004, 00:03:12 »