Multivalue table in lua

lua

Solution

Tables can hold other tables, so you can store as many variables as you need in each message.

Instead of:

table.insert(queue, datum1)

You can have:

local message = {datum1, datum2}
table.insert(queue, message)

Or simply:

table.insert(queue, {datum1, datum2})

Including as many "parts" to the message as you want. On the receiving end, you can refer to the message parts by index:

print('foo:', message[1], 'bar:', message[2])

Or unpack the elements:

local foo, bar = unpack(message) -- this is `table.unpack` in Lua 5.2
print('foo:', foo, 'bar:', bar)

Or you could use named fields in the message:

local message = {
      foo = datam1,
      bar = datum2,
}
table.insert(queue, message)

So on and so forth.

Problem

I'm doing some parallel operations in lua. one thread for receiving, one for processing and one for sending again. To pass the data between threads i have been using tables. Sadly, now i need to pass more than one variable. How do i create a "Multivalue table" ( a table where i can have multiple values per key) without it impacting performance too much, and is there a more efficient way than using tables? Simplified code so far: ``` sendQueue = {} processQueue = {} function recieveLoop() while true do Wait For recieve table.insert(processQueue, recievedText) end end function processLoop(sender, text, raw) while true do for key,value in pairs(processQueue) do processData table.insert(recieveQueue, raw) end end end ``` And then the same for receiveLoop all of these 3 functions are threaded and run independently of each other.

Original source