Page 1 of 1

Metatables across threads

Posted: Sun Jan 31, 2021 2:23 pm
by IMP1
I'm using a thread to perform level generation so I can show progress and keep on rendering things while it's happening.

But the final object being passed to the main thread is a nested table and it seems that the metatables of the sub-tables are not preserved "through" the channel.

I can instead pass the necessary data and construct the objects after the level generation, but it seems to be like this makes using the separate thread (slightly) less useful.

Is this a feature of channels? Is it a feature that is likely to be changed? Or have I just missed something in my code?

Thanks to anyone who can help!

Re: Metatables across threads

Posted: Sun Jan 31, 2021 2:56 pm
by grump
Unfortunately, metatables are not preserved across channels. They wouldn't be very useful anyway, because you can't send (raw) functions over channels.

One possible and efficient solution is to build a table of all required metatables in all threads, and include an identifer for the metatable when you send a table. You can then just call setmetatable on the receiving end, without the need to reconstruct the object.

Sending metatables over the channel is possible too, but you have to string.dump() all functions, and loadstring() them on the receiving end, and upvalues will be lost.

Re: Metatables across threads

Posted: Sun Jan 31, 2021 3:41 pm
by IMP1
Ah, that clears things up. Good to know about functions also not being sent over channels. Thanks a lot!