0
0
Redisquery~10 mins

Lua script syntax in Redis - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Lua script syntax in Redis
Start Script
Define Variables
Use Redis Commands
Return Result
End Script
A Lua script in Redis starts, defines variables, runs Redis commands, returns a result, and ends.
Execution Sample
Redis
local val = redis.call('GET', KEYS[1])
if val == false then
  return 'No value'
end
return val
This script gets a key's value; if missing, returns 'No value', else returns the value.
Execution Table
StepActionEvaluationResult
1Call redis.call('GET', KEYS[1])KEYS[1] = 'mykey'val = 'hello'
2Check if val == falseval = 'hello'Condition false
3Return valval = 'hello'Output: 'hello'
4End scriptScript ends
💡 Script ends after returning the value or 'No value' if key missing
Variable Tracker
VariableStartAfter Step 1After Step 2Final
valnil'hello''hello''hello'
Key Moments - 2 Insights
Why does redis.call return false if the key does not exist?
redis.call returns false when the key is missing, so the script checks val == false to handle missing keys (see execution_table step 2).
What happens if we forget to return a value in the script?
If no return is given, Redis returns nil, which can cause confusion. Always use return to send a result back (see execution_table step 3).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'val' after Step 1?
Anil
Bfalse
C'hello'
D'No value'
💡 Hint
Check the 'Result' column in Step 1 of the execution_table.
At which step does the script decide what to return?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Action' and 'Evaluation' columns in Step 2 of the execution_table.
If the key does not exist, what would the script return?
A'No value'
B'hello'
Cnil
Dfalse
💡 Hint
Refer to the script code in execution_sample and the condition in execution_table step 2.
Concept Snapshot
Lua scripts in Redis:
- Use redis.call('COMMAND', args) to run Redis commands
- KEYS and ARGV hold input keys and arguments
- Use local variables to store results
- Return a value with return statement
- redis.call returns false if key missing
Full Transcript
This visual execution shows how a Lua script runs in Redis. The script starts by calling redis.call to get a key's value. If the key does not exist, redis.call returns false. The script checks this and returns 'No value' if missing. Otherwise, it returns the actual value. Variables like 'val' store intermediate results. The script ends after returning a value. This step-by-step trace helps beginners see how Lua scripts interact with Redis commands and handle missing keys.