Lua:tonumber

From Cheat Engine
Jump to navigation Jump to search

<> Lua API Reference

function tonumber(value) : number

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.

Function Parameters[edit]

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[edit]

Number — The converted number.

Returns nil if the value cannot be converted to a valid number.

Description[edit]

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[edit]

Convert a numeric string[edit]

1 local value = tonumber("123")
2 
3 print(value)

Convert a decimal string[edit]

1 local value = tonumber("12.5")
2 
3 print(value + 2.5)

Check if conversion succeeded[edit]

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[edit]

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[edit]

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[edit]

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[edit]

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[edit]

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[edit]

 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[edit]

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

Main Pages

Core Lua documentation entry points

Lua
Script Engine