Lua, a lightweight and versatile scripting language, offers a concise set of data types. Understanding these types is crucial for effective Lua programming.
Lua provides eight basic data types:
Lua uses double-precision floating-point format for numbers. It doesn't distinguish between integers and floats.
local integer = 42
local float = 3.14
local scientific = 1.2e-3
Strings in Lua are immutable sequences of bytes. They can be delimited by single or double quotes.
local single_quoted = 'Hello'
local double_quoted = "World"
local multi_line = [[
This is a
multi-line string
]]
Boolean values in Lua are true
and false
. Note that nil
is considered false in boolean contexts.
local is_active = true
local has_error = false
Tables are the only data structuring mechanism in Lua. They can be used to represent arrays, dictionaries, objects, and more.
local array = {1, 2, 3, 4, 5}
local dictionary = {name = "John", age = 30}
local mixed = {1, "two", {3}, four = 4}
For more advanced usage of tables, refer to Lua Table Basics.
Functions in Lua are first-class values, meaning they can be assigned to variables, passed as arguments, and returned from other functions.
local function greet(name)
return "Hello, " .. name
end
local result = greet("Lua")
To dive deeper into functions, check out Lua Function Basics.
Lua provides the type()
function to determine the type of a value:
print(type("Hello")) -- Output: string
print(type(42)) -- Output: number
print(type({})) -- Output: table
print(type(true)) -- Output: boolean
print(type(nil)) -- Output: nil
type()
function for runtime type checking when necessary.Understanding Lua's data types is fundamental to writing efficient and error-free code. As you progress, you'll find that Lua's flexible type system allows for powerful and expressive programming paradigms.
For more information on working with different data types, explore Lua Type Conversion and Lua String Manipulation.