Range Over Channels in Lua

Our first example demonstrates how to iterate over values received from a channel. In Lua, we don’t have built-in channels, but we can simulate this behavior using coroutines and tables.

local queue = {"one", "two"}

-- Function to simulate sending values to a channel
local function send_values(queue)
    for _, value in ipairs(queue) do
        coroutine.yield(value)
    end
end

-- Create a coroutine for sending values
local sender = coroutine.create(function() send_values(queue) end)

-- Main function
local function main()
    -- This loop iterates over each element received from the sender coroutine
    while true do
        local status, value = coroutine.resume(sender)
        if not status then
            break
        end
        print(value)
    end
end

-- Run the main function
main()

To run the program, save it as range_over_channels.lua and use the lua command:

$ lua range_over_channels.lua
one
two

In this example, we’ve simulated the behavior of channels using coroutines. The send_values function acts as a generator, yielding values from the queue. The main loop then resumes the coroutine to receive each value until there are no more values to process.

This example also demonstrates how we can iterate over a finite set of values. Once all values have been processed, the loop terminates, similar to how the original example terminates after receiving all values from a closed channel.