Data Types
Anonymous contributor
Published Aug 16, 2023
Contribute to Docs
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.
Data Classes
Lua has eight basic data types, which include: boolean
, function
, nil
, number
, string
, table
, thread
, 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
type()
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"
Type Conversion
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”
The tonumber()
function is used to convert any data type to a number type:
totalGuests = '30'print(tonumber(totalGuests) / 5)-- This prints 6
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Lua on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Lua
Learn the basics of Lua, a general-purpose programming language used for building games, web apps, and developer tools.Beginner Friendly4 hours