Lua: Coercion

From Mario Fan Games Galaxy Wiki
Add to this template
 Standardwikimessagebox.png This article assumes the use of Lua 5.1.

Information may not be accurate or may need revision if you are using a different version.

Coercion is the automatic conversion of one datatype into another. Generally, Lua attempts this when some operation is carried on one or more datatypes; the operation itself determines what type it will try to convert to, eg. numbers for '+' and strings for '..'. If coercion fails, Lua may issue an error if the original datatype is not expected by the operation.

As a special note, in a few instances, Lua will not attempt coercion: table indexing and comparisons. In these cases, the tostring() and tonumber() functions must be used if you know the datatypes may be different. The equality operator == will accept two differing types, but will always return false; likewise, ~= will always return true. The inequality operators <, <=, >, and >= cannot compare differing types and will issue an error. As, for example, "2" and 2 are different entries in a table, coercion would more than likely be undesired. Lua will only coerce numbers during concatenation; other types must be explicitly converted with tostring().

Generally it is a good idea to use tonumber() and tostring() whenever possible to ensure proper coercion. Depending on your needs, you may be better served using string.format() to convert numbers into strings, as you have additional formatting options available such as how many decimal points to keep or whether to add leading zeros.

Coercion types

Any datatype may be coerced into a boolean. nil and false will be treated as false; true and any other datatype is true regardless of their value.

Any datatype may be coerced into a string, either automatically or with tostring(). Numbers, strings, booleans, and nil will appear exactly as they would in the source code. Userdata, functions, threads, and tables will instead print out their type followed by their memory address; in the case of tables, their __tostring metamethod can be used to change how they are converted into a string.

Strings may or may not be coercible into numbers, automatically or with tonumber(); in order for this to be possible, the string must follow Lua's number literal rules. tonumber will return nil if it cannot convert a type.