Hello! Simple module today! This is a module I made with the intention of using it as a better tonumber() specifically for user input.
How it works:
Let’s say you input “ABC1ADE321”, it would return from tonumber() as NIL.
If you did the same with ToNumber+:
It would return 1321. Which are the numbers on that string.
How to use:
local toNumber = require(game.ReplicatedStorage["ToNumber+"])
local userInput = "I want to spend 1000 coins"
local whatShouldBeEndResult = 1000
local converted = toNumber:Convert(userInput)
if converted == whatShouldBeEndResult then
print("It's working properly.") -- It is btw.
end
Also, you can have a “method” when requesting the function;
by sending “string” as the second argument, it will return the number as a string instead of a number.
Example:
local converted = toNumber:Convert(userInput, "string")
So why should I use toNumber:Convert(userInput, "string") over the trivial userInput:gsub("%D", '')?
Is there any reason why you’re using : over . when you’re not using self?
This doesn’t seem to account for deciamls (./,), scientific (E) notation, signed (aka negative) numbers, Infinity and NaN or hexadecimal/binary literals that tonumber/__tonumber has.
I mean that : implicitally passes self as an argument. : in Lua usually implies that it’s a method of an object.
Aside from it being evaluated once (and the __namecall metamethod in Roblox’s implemention) x:y(...) is the same as x.y(x, ...). and function x:y(...) is the same as function x.y(self, ...)
You should be using . unless you’re going to use self.
While I don’t believe there’s any difference in performance, Lua style guides tend to lean towards using . when not using self. It’s good to follow a universal standard even though I know you’re used to calling functions on Roblox objects with :.
It really shouldn’t be confusing? There is no syntactical difference in writing or calling the functions…
No there’s no problem. Roblox uses it all the time to make the difference between methods and properties clearer to the user. There’s no problem using the colon notation as long as you’re aware of the variable that gets passed through.
Using colons both when calling and defining the function is fine. It’s mostly down to a style choice, and if it makes it clearer to yourself that the table value is a function and not any other data type, then that’s a fair justification.
There are more important issues like all the additional number formats:
local function ToNumber(String)
return
(not String or type(String) ~= "string" and (String and type(String) == "number" and String or 0)) or
tonumber(String) or tonumber(string.match(String, "%-?%d+%.?%d*")) or 0
end