Conditional logic

What if your client behaviour depends on the results of previous requests?

Let’s imagine a coin tossing game. Our client bets on head or tails. The server tosses the coin and returns the result as one of two possible text messages:

Toss result: heads!


Toss result: tails!

If the client wins, he should then request `won.php`, otherwise `lost.php`. This means that the client has to make a request to the server to make it perform the coin flip, then read the returned result from the server and act upon its contents, either loading “won.php” or “lost.php”.

-- Define a list of coin sides
local coin_sides = {"heads", "tails"}
-- Pick a random coin side
local coin_side = coin_sides[math.random(#coin_sides)]
-- Tell server what we're betting on.
local response = http.request_batch({
    {"GET", "" .. coin_side, response_body_bytes=1024}
-- Extract a coin toss result from server response
local toss_result = response[1].body:match("Toss result: (%w+)!")
-- Check that toss_result contains expected data
if not (toss_result == "heads" or toss_result == "tails") then
    -- Print error to log
        "server returned unexpected response: "
        .. (toss_result or response[1].body) -- toss_result would be nil if find() fails
else -- Toss result is valid, go on
    -- If coin toss result matches our bet, request a victory page
    if toss_result == coin_side then'Won!')
            {"GET", ""}
    else -- Otherwise we've lost'Lost!')
            {"GET", ""}

See also:

Feedback and Knowledge Base