0
0
Redisquery~30 mins

Lua script syntax in Redis - Mini Project: Build & Apply

Choose your learning style9 modes available
Basic Lua Scripting in Redis
📖 Scenario: You are managing a Redis database for a small online store. You want to use Lua scripts inside Redis to perform atomic operations on your data.
🎯 Goal: Build a simple Lua script in Redis that increments a product's stock count safely.
📋 What You'll Learn
Create a Lua script that increments a stock count for a product key
Use Redis commands inside the Lua script
Pass the product key and increment value as arguments to the script
Return the new stock count after increment
💡 Why This Matters
🌍 Real World
Lua scripts in Redis are used to perform multiple commands atomically, which is useful in inventory management systems to avoid race conditions.
💼 Career
Knowing how to write Lua scripts in Redis is valuable for backend developers and DevOps engineers working with Redis to ensure data consistency and performance.
Progress0 / 4 steps
1
Create a Lua script variable
Create a Lua script string variable called lua_script that contains a Redis command to get the current stock count of a product key passed as KEYS[1]. Use redis.call('GET', KEYS[1]) inside the script.
Redis
Need a hint?

Use redis.call to run Redis commands inside Lua scripts.

2
Add increment argument
Add a Lua variable increment inside lua_script that gets the increment value from ARGV[1]. Use tonumber(ARGV[1]) to convert it to a number.
Redis
Need a hint?

Use ARGV[1] to access script arguments passed after keys.

3
Calculate new stock count
Modify lua_script to convert stock to a number (use tonumber(stock) or 0) and add increment to it. Store the result in a variable called new_stock.
Redis
Need a hint?

Use tonumber(stock) or 0 to handle the case when stock is nil.

4
Update stock and return new value
Complete lua_script by setting the new stock count in Redis using redis.call('SET', KEYS[1], new_stock) and then return new_stock.
Redis
Need a hint?

Use redis.call('SET', KEYS[1], new_stock) to update the stock count.