Casting

Contents

Casting#

Lua does few implicit conversions and many explicit ones.

From / to

How

any to string

tostring(x) or string.format("%s", x).

string to number

tonumber(s); returns nil on failure.

string in base N

tonumber(s, 16) for hex (or any base 2..36).

number to integer (truncate)

math.floor(x) or x // 1.

number to integer (ceil)

math.ceil(x).

to clean boolean

x and true or false.

Arithmetic between a number and a string that looks like a number works in 5.1 / 5.2 / 5.3 but raises in 5.4. The operator does not rely on this; use tonumber first.

print("3" + 1)               -- 4 in 5.3, error in 5.4
print(tonumber("3") + 1)     -- 4, portable

References#

  • number for the integer / float distinction.

  • string for string.format formatting codes.