Select in Lua
Lua doesn’t have built-in concurrency primitives like Go’s goroutines and channels. However, we can simulate similar behavior using Lua’s coroutines and a custom implementation of channels. We’ll use the luaposix
library for sleep functionality.
This Lua code simulates the behavior of the original example. Here’s how it works:
We define a
makeChannel
function to simulate Go’s channels. It uses a queue to store values and a list of waiting threads.We create two channels,
c1
andc2
.The
asyncSend
function simulates a goroutine that sends a value after a delay. It returns a coroutine.We start two “goroutines” that will send “one” after 1 second and “two” after 2 seconds.
The
select
function simulates Go’sselect
statement. It tries to receive from each channel and calls the appropriate handler when a value is available.In the main loop, we use our
select
function to await values from both channels simultaneously, printing each one as it arrives.Finally, we resume our “goroutines” to start the sending process.
To run this program, save it as select.lua
and execute it with Lua:
Note that the total execution time will be about 2 seconds, as both the 1 and 2 second delays execute concurrently.
This example demonstrates how to simulate Go’s select and channel behavior in Lua using coroutines. While it’s not as elegant or efficient as Go’s built-in concurrency features, it provides a similar functionality.