Lua scripts are programs written in Lua, which is a lightweight, high-level, and embeddable scripting language. It was designed to be fast, simple, and flexible, making it popular for extending applications and embedding into larger systems.
Here’s a breakdown:
- Lightweight & Fast – Very small footprint, ideal for embedding in applications like games or databases.
- Embeddable – Often used as a scripting engine inside larger systems (e.g., games, Redis, Nginx).
- Simple Syntax – Easy to learn, similar to Python and JavaScript in readability.
- Extensible – Can be extended with C, C++, or Java libraries.
- Dynamic Typing – No need to declare variable types.
- Garbage Collection – Automatic memory management.
- Game Development – Popular in game engines (e.g., Roblox, World of Warcraft addons, CryEngine).
- Databases – Redis supports Lua scripts for transactions and complex operations.
- Web Servers – Nginx (via OpenResty) uses Lua for request handling and customization.
- Embedded Systems – Its lightweight design makes it suitable for IoT and embedded devices.
- Configuration & Automation – Applications use Lua for customization through config files and automation.
-- Hello World in Lua
print("Hello, World!")
-- Simple loop
for i = 1, 5 do
print("Number: " .. i)
end
-- Function
function add(a, b)
return a + b
end
print("Sum: " .. add(10, 20))Output:
Hello, World!
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Sum: 30
👉 In short, Lua scripts are small programs that automate tasks, extend applications, or add logic inside larger systems.
Redis supports Lua because sometimes you need to run multiple Redis commands atomically (all-or-nothing) or perform logic close to the database to reduce network calls.
- Atomic execution → A Lua script in Redis runs as a single atomic operation (no other command runs in between).
- Reduce round-trips → Instead of sending multiple commands one by one, you put the logic in Lua and send once.
- More powerful logic → You can add loops, conditions, and calculations directly in Redis.
You use the EVAL command.
EVAL "return 'Hello from Lua!'" 0📌 Output:
"Hello from Lua!"
Here:
"return 'Hello from Lua!'"is the Lua script.0means no Redis keys are passed in.
Let’s say you want to set a key only if it doesn’t exist.
EVAL "if redis.call('EXISTS', KEYS[1]) == 0 then
return redis.call('SET', KEYS[1], ARGV[1])
else
return 'Key already exists'
end" 1 mykey myvalueExplanation:
1→ number of keys (heremykeyis the key).mykey→ the key passed to the script (KEYS[1]).myvalue→ argument passed (ARGV[1]).
EVAL "return redis.call('INCRBY', KEYS[1], ARGV[1])" 1 user:123:score 10📌 This increments user:123:score by 10.
If you run again, it adds another 10.
- You can do transactions with logic.
- Avoid writing multiple round-trips in your app code.
- Very fast since script runs inside Redis itself.
👉 So, Lua scripting in Redis is like writing “mini-programs” inside Redis for atomic, efficient operations.