Lua Variables
Creating Variables
Lua variables do not require explicit type declarations.
hoge = 10
foo, bar = 10, 20
Assignments are allowed anywhere. Variables are global unless declared with local.
Variable names must begin with a letter or _, may contain digits after the first character, and cannot use reserved words such as if, while, or function.
Use = for assignment and == for equality comparison.
Displaying Values
Use print() to display one or more values.
hoge = 10
piyo = 20
print(hoge, piyo)
Concatenate text with .., and use string.format() for formatted output.
hoge = 10
print(string.format("hoge in decimal is %d", hoge))
print("hoge in hexadecimal is " .. string.format("%x", hoge))
Common format specifiers include %d, %u, %o, %x, %f, %c, and %%.
Arithmetic
Lua supports the usual arithmetic operators.
| Operator | Meaning |
|---|---|
+ |
addition |
- |
subtraction |
* |
multiplication |
/ |
division |
% |
remainder |
^ |
exponentiation |
x = 10
y = 3
print(x + y)
print(x % y)
print(2 ^ 3)
Dynamic Types
In Lua, values have types and variables can refer to values of different types over time.
| Type | Meaning |
|---|---|
nil |
no value |
boolean |
true or false |
number |
numeric value |
string |
text |
function |
function |
userdata |
user-defined data |
thread |
coroutine thread |
table |
table |
Inspect a value with type().
hoge = nil
print(type(hoge))
hoge = "Hello"
print(type(hoge))
hoge = 33
print(type(hoge))
Reading Keyboard Input
Use io.read() to read input and io.write() to display a prompt without an automatic newline.
io.write("Enter a meter value: ")
meter = io.read()
answer = meter * 3.2
print(meter .. " meters is " .. answer .. " feet.")
Lua also supports multiple assignment, which makes swapping values concise.
hoge, piyo = 10, 5
hoge, piyo = piyo, hoge
print(hoge, piyo)