Lua:tonumber
Jump to navigation
Jump to search
Converts a value to a number.
If the value can be converted, tonumber returns the resulting number. If the value cannot be converted, it returns nil.
Contents
- 1 Function Parameters
- 2 Returns
- 3 Description
- 4 Examples
- 4.1 Convert a numeric string
- 4.2 Convert a decimal string
- 4.3 Check if conversion succeeded
- 4.4 Handle invalid input
- 4.5 Convert a MemoryRecord value
- 4.6 Use tonumber before comparing values
- 4.7 Convert text field input
- 4.8 Use tonumber with readInteger fallback
- 4.9 Parse a number from a string table
- 4.10 Use tonumber for safe arithmetic
Function Parameters
| Parameter | Type | Description |
|---|---|---|
| value | Any | The value to convert to a number. This is commonly a string, but numbers can also be passed directly. |
Returns
Number — The converted number.
Returns nil if the value cannot be converted to a valid number.
Description
tonumber is commonly used when a value is stored as text but needs to be used in numerical calculations.
This is useful when working with user input, memory record values, text fields, string parsing, or other functions that return values as strings.
Examples
Convert a numeric string
1 local value = tonumber("123")
2
3 print(value)
Convert a decimal string
1 local value = tonumber("12.5")
2
3 print(value + 2.5)
Check if conversion succeeded
1 local value = tonumber("500")
2
3 if value ~= nil then
4 print("Converted value: " .. tostring(value))
5 else
6 print("The value is not a valid number")
7 end
Handle invalid input
1 local value = tonumber("hello")
2
3 if value == nil then
4 print("Could not convert string to number")
5 end
Convert a MemoryRecord value
1 local record = AddressList.getMemoryRecordByDescription("Player Health")
2
3 if record ~= nil then
4 local value = tonumber(record.Value)
5
6 if value ~= nil then
7 print("Health + 100 = " .. tostring(value + 100))
8 end
9 end
Use tonumber before comparing values
1 local input = "75"
2 local value = tonumber(input)
3
4 if value ~= nil and value >= 50 then
5 print("Value is high enough")
6 end
Convert text field input
1 local text = "250"
2 local amount = tonumber(text)
3
4 if amount ~= nil then
5 print("Amount: " .. tostring(amount))
6 end
Use tonumber with readInteger fallback
1 local textAddress = "game.exe+12345"
2 local rawValue = readInteger(textAddress)
3 local value = tonumber(rawValue)
4
5 if value ~= nil then
6 print("Value: " .. tostring(value))
7 end
Parse a number from a string table
1 local values = { "10", "20", "invalid", "40" }
2
3 for i, text in ipairs(values) do
4 local number = tonumber(text)
5
6 if number ~= nil then
7 print("Parsed: " .. tostring(number))
8 else
9 print("Invalid number at index " .. tostring(i))
10 end
11 end
Use tonumber for safe arithmetic
1 local a = tonumber("10")
2 local b = tonumber("5")
3
4 if a ~= nil and b ~= nil then
5 print(a + b)
6 end