Lua, like Python and Ruby, is a dynamically typed language, which means the data type does not have to be explicitly declared with the variable.
Lua has eight basic data types, which include:
userdata. Some of the most commonly used are demonstrated below.
-- A booleanflag = false-- A string, strings can be declared with single or double quotesname = "John Doe"-- A number, in Lua there is not an integer typenum = 13-- A functionfunction foo () return "bar" end
Lua has a built-in
type() function to retrieve the data type.
location = 'Maple Road'print(type(location)) -- This outputs "string"print(type(12/3)) -- This outputs "number"
In Lua, type coercion automatically happens when strings and numbers are concatenated or when a string with a numeric value appears in an arithmetic expression.
-- The first type coercion is used in a concatenation to change a number to a string.temperature = 56print('Today’s temperature is ' .. temperature .. ' degrees.') -- This prints “Today’s temperature is 56 degrees.”-- The second type of coercion is used during arithmetic expressions.print('53' + 7)-- This outputs 60 because it converted “53” to a number for the arithmetic.
Types can be manually converted by using the
tostring() function to convert any data type to a string type:
player1Pts = 55print('Player 1 has ' .. tostring(player1Pts) .. ' points')-- This prints “Player 1 has 55 points”
tonumber() function is used to convert any data type to a number type:
totalGuests = '30'print(tonumber(totalGuests) / 5)-- This prints 6
- Anonymous contributorAnonymous contributor3 total contributions
- Anonymous contributor