converting string to a number?

Discuss using and improving Lua and the Lua Player specific to the PSP.

Moderators: Shine, Insert_witty_name

Post Reply
psiko_scweek
Posts: 42
Joined: Sat Nov 12, 2005 2:30 am

converting string to a number?

Post by psiko_scweek »

ok, is there anyways i can convert a string to a number?

my game has a string and when i try to assign it to an array i get the message saying something bout trying to load from a nil value. the string is '12' so it shouldnt be too hard to convert to an actual number format for the array to understand right?

sorry if that doesnt make any sense

~PSIKO
chaos
Posts: 135
Joined: Sun Apr 10, 2005 5:05 pm

Post by chaos »

i don't know if there's an official way to do this, but here's how i've done it in my game..

if someString+0 > 20 then blahblah end

when you put +0 on the end, it automatically converts to a number..
Chaosmachine Studios: High Quality Homebrew.
psiko_scweek
Posts: 42
Joined: Sat Nov 12, 2005 2:30 am

yah!!

Post by psiko_scweek »

thanks Chaos! works like a charm..
i knew it was going to be something simple....lol
again thanks!!

regards,
~PSIKO
haust
Posts: 25
Joined: Sat Oct 01, 2005 12:37 am
Location: France

Post by haust »

there is also the tonumber(MyVar) function available for this kind of conversion....
psiko_scweek
Posts: 42
Joined: Sat Nov 12, 2005 2:30 am

eh!?

Post by psiko_scweek »

where was that little function hidden at?! i swear i looked through the entire manual, and didnt see it!.

thanks haust that too works. lol.

Regards,
PSIKO
alexis
Posts: 11
Joined: Mon Nov 14, 2005 10:21 am
Location: between neptune and mars

Post by alexis »

chaos wrote:i don't know if there's an official way to do this, but here's how i've done it in my game..

if someString+0 > 20 then blahblah end

when you put +0 on the end, it automatically converts to a number..
According to the "bible", the add methamethod have the following lua equivalent behavior:

Code: Select all

 function add_event (op1, op2)
   local o1, o2 = tonumber(op1), tonumber(op2)
   if o1 and o2 then  -- both operands are numeric?
     return o1 + o2   -- `+' here is the primitive `add'
   else  -- at least one of the operands is not numeric
... go to the metatable of op1 or op2 ...
So I think that "myString+myInteger" or "myInteger+myString" are perfectely official. But the interpreter could raise an error if "myString" is not convertible to a number in base 10.
It could be a good reason to be in favor of an explicitely call to the "tonumber" function to convert "myString".

Regards.
Ho no ... !! I make the same bug again !!!
Post Reply