This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
mrSLIMEguy's profile picture

[Lua] How do i multitask?

Started by mrSLIMEguy, 30 October 2012 - 05:16 AM
mrSLIMEguy #1
Posted 30 October 2012 - 06:16 AM
Does anyone know how to make two codes run at the same time?
I made a chat with rednet, but you must look at the monitor
if i add code, it only refreshes when i post something…
what do i do?
PixelToast #2
Posted 30 October 2012 - 06:20 AM
coroutines/parallel API are your friend

function func1()
  while true do
    --stuff
  end
end
function func2()
  while true do
    --more stuff
  end
end
parallel.waitForAny(func1,func2)
Pharap #3
Posted 30 October 2012 - 07:05 AM
In this circumstance, I would make use of os.pullEvent().

If you set a bit of code that renders the screen (eg a function called draw),
then check for an event, you can test if that event was a rednet message or a key-press.
If it was a message, you can add it to a table storing messages to be displayed, if it was a key, you either add a character to the user's current message, send the user's message or exit the conversation.

example code (this is an example, it won't necessarily work):

local messagestoshow = {}
local messagessent = {}
local messagesreceived = {}
local yourid = os.getComputerID()
local otherid = 5
local msgbuffer = ""
while true do
Draw()
local e, var1,var2,var3 = os.pullEvent()
if e=="rednet_message" then
local id = var1
local msg = var2
local distance = var3
if id == otherid then
messagesreceived[table.maxn(messagesreceived)+1] = msg
messagestoshow[table.maxn(messagestoshow)+1] = msg
end
elseif e=="char" then
local newchar = arg1
msgbuffer = msgbuffer..newchar
elseif e=="key" then
newkey = var1
if newkey == keys.enter then
rednet.send(otherid,msgbuffer)
msgbuffer = ""
end
end
end

If you need me to go through what any of this does, don't be afraid to ask, rednet can be tricky at times, particularly with messaging clients.