| View previous topic :: View next topic |
| Author |
Message |
psiko_scweek
Joined: 12 Nov 2005 Posts: 42
|
Posted: Fri Nov 18, 2005 3:45 am Post subject: converting string to a number? |
|
|
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 |
|
| Back to top |
|
 |
chaos
Joined: 10 Apr 2005 Posts: 135
|
Posted: Fri Nov 18, 2005 2:22 pm Post subject: |
|
|
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. |
|
| Back to top |
|
 |
psiko_scweek
Joined: 12 Nov 2005 Posts: 42
|
Posted: Fri Nov 18, 2005 3:24 pm Post subject: yah!! |
|
|
thanks Chaos! works like a charm..
i knew it was going to be something simple....lol
again thanks!!
regards,
~PSIKO |
|
| Back to top |
|
 |
haust
Joined: 01 Oct 2005 Posts: 25 Location: France
|
Posted: Sat Nov 19, 2005 1:53 am Post subject: |
|
|
| there is also the tonumber(MyVar) function available for this kind of conversion.... |
|
| Back to top |
|
 |
psiko_scweek
Joined: 12 Nov 2005 Posts: 42
|
Posted: Sat Nov 19, 2005 3:20 am Post subject: eh!? |
|
|
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 |
|
| Back to top |
|
 |
alexis
Joined: 14 Nov 2005 Posts: 11 Location: between neptune and mars
|
Posted: Sat Nov 19, 2005 7:44 pm Post subject: |
|
|
| 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: |
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 !!! |
|
| Back to top |
|
 |
|