Page 1 of 2

Int to String

Posted: Sat Jul 11, 2015 4:23 pm
by CanadianGamer
Hi everyone,

I'm sorry if it is a dumb question but in the game I'm making I want to do a level counter but I don't know how to format an int to a string.

Thanks for any advice you have

Re: Int to String

Posted: Sat Jul 11, 2015 4:30 pm
by arampl
tostring(number)

Re: Int to String

Posted: Sat Jul 11, 2015 5:02 pm
by CanadianGamer
thanks

Re: Int to String

Posted: Sat Jul 11, 2015 6:17 pm
by davisdude
Conversely, you can do tonumber( string ) to check if a string is a valid number; something far better than my previous (and very hack-ish) method:

Code: Select all

function isNumber( str )
    if pcall( function() return str + 0 end ) then
        return str + 0
    end
    return false
end

Re: Int to String

Posted: Fri Jul 17, 2015 11:59 pm
by Positive07
davisdude wrote:-snip-
isnt [manual]tonumber[/manual] far better?

Also 5.3 return ints and floats in different formats when using [manual]tostring[/manual] so you may prefere [manual]string.format[/manual] and some numeral format like %i

Re: Int to String

Posted: Sat Jul 18, 2015 12:05 am
by Nixola
Positive07 wrote:isnt tonumber far better?
davisdude wrote:; something far better than my previous (and very hack-ish) method: -snip-

Re: Int to String

Posted: Sat Jul 18, 2015 12:17 am
by Positive07
Nixola wrote:-snip-
I read the exact opposite, sorry hahaha

Re: Int to String

Posted: Sat Jul 18, 2015 9:35 pm
by TsT
davisdude wrote:Conversely, you can do tonumber( string ) to check if a string is a valid number; something far better than my previous (and very hack-ish) method:

Code: Select all

function isNumber( str )
    if pcall( function() return str + 0 end ) then
        return str + 0
    end
    return false
end
Hello,

You code is ulgy and be able to break the check with metatable/__add meta handler.

Code: Select all

local hack=10
print(isNumber(hack)) -- print 10, as expected

local hack="hack"
print(isNumber(hack)) -- print false, as expected

local mt = {}
local hack = setmetatable({}, mt)
mt.__add = function() return hack end
mt.__tostring = function() return "p0wn3d" end
print(isNumber(hack)) -- print p0wn3d, instead of false

Re: Int to String

Posted: Sat Jul 18, 2015 9:54 pm
by bartbes
Nixola wrote:
Positive07 wrote:isnt tonumber far better?
davisdude wrote:; something far better than my previous (and very hack-ish) method: -snip-
TsT wrote:You code is ulgy and be able to break the check with metatable/__add meta handler.
Reading is difficult!

Re: Int to String

Posted: Sat Jul 18, 2015 10:15 pm
by airstruck
bartbes wrote:Reading is difficult!
It's the ulgy trooth