How to change strings into number

simple as the title, I just need to know how to turn One into 1 and Two into 2 and so on.

To change a string into a number you can use the function ‘tonumber’, which takes one arg and will error if you try to call something that isn’t a number.

no like change One to 1 because tonumber(“One”) turns One into nil

Ok so you want for exemple 2 to turn into “Two”

opposite way around like Two into 2

im pretty sure you have to do each number separately. Can’t think of another efficient way to do it sorry

You would have to store the numbers in a dictionary. There are likely other ways (using 3rd party modules), but this is the only way I can of.

local numbers = {
    ["Zero"] = 0,
    ["One"] = 1,
    ["Two"] = 2,
    ["Three"] = 3,
    ["Four"] = 4,
    ["Five"] = 5,
    ["Six"] = 6,
    ["Seven"] = 7,
    ["Eight"] = 8,
    ["Nine"] = 9,
}

print(numbers.One) --> 1

I understand now, This is a solution but you will have to add every number individually.

function NumConverter(number)
    local Numbers = {
        ['One'] = 1,
        ['Two'] = 2,
    }

    return Numbers[number] or "Unknown"
end
print(NumConverter('One'))

thanks, it works! i just wondering is numbers.One that same as numbers[1]

yeah
its the same thing, just that the second option finds the key in the table

They are different, numbers[1] would refer to an element with the index of 1, not One. But, you can do this if you’d like:

local numbers = {
    [0] = "Zero",
    "One",
    "Two",
    "Three",
    "Four",
    "Five",
    "Six",
    "Seven",
    "Eight",
    "Nine",

    ["Zero"] = 0,
    ["One"] = 1,
    ["Two"] = 2,
    ["Three"] = 3,
    ["Four"] = 4,
    ["Five"] = 5,
    ["Six"] = 6,
    ["Seven"] = 7,
    ["Eight"] = 8,
    ["Nine"] = 9,
}

print(numbers.One) --> 1
print(numbers[1]) --> "One"

Here is a version that lets you do 1 or ‘One’. But you need to add the extra numbers yourself.

(Edit: And it’s really optimized)

function NumConverter(number)
    local Numbers = {
        ['One'] = 1,
        ['Two'] = 2,
    }

	for i,v in pairs(Numbers) do
		if number == v then
			return i
		end
	end
    return Numbers[number] or "Unknown"
end
print(NumConverter(1)) -- 'One'
print(NumConverter('One')) -- 1

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.