CC: Tweaked

CC: Tweaked

42M Downloads

Tables passed by reference in os.pullEvent

hugeblank opened this issue ยท 3 comments

commented

Minecraft Version

1.19.x

Version

1.103.1

Details

I have a computer on SwitchCraft that has multiple programs running in parallel that heavily utilize the chatbox functionality. I discovered this issue when one of the programs I had made modified a table that it got from os.pullEvent. Every program that then pulled that event received the modified table. By the time I realized the problem I had forgotten that one of the programs modified the table, which left me very confused.

Replicate this issue with an advanced computer:

  1. Write a simple program that prints out a custom event:
while true do
  print(os.pullEvent("custom"))
end
  1. run that program on 2 multishell tabs
  2. on the third tab, open the REPL and run os.queueEvent("custom", {})
  3. Check back on the two tabs.
    The outcome is that the two table ids are identical

Expected outcome:
The two tables should be distinct from each other. Modification of the table in one program, or in one function should not affect another. The reason I think this is because the same thing is done for queueEvent. The table is cloned, and made separate from the original.

commented

I don't think this is something we can fix without breaking some user program. I think the lesson here is don't mutate things you get from events!

commented

I'm curious what user program would utilize this as a feature. how would things break?

commented
local function middleware()
   while true do
      local event, sender, message, protocol = os.pullEvent("rednet_message")
      if type(message) == "table" then message.known = sender == 1 end
   end
end

local function solver()
   while true do
      local event, sender, message, protocol = os.pullEvent("rednet_message")
      if type(message) == "table" and message.known then ... end
   end
end

parallel.waitForAll(middleware, solver)

A bit not sane example but should show how someone program could be using it.