Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Is there anything similar to zip() from python in lua?

something like this:

local peoples = { 'joe', 'jogn', 'gfajkg' }
local secrets = { 'agag', 'gafggf', 'gagfdg' }
local reasons = { 'sometyhing', 'another thing', 'ffszdgsg' }

for index, name in next, peoples do
	local secret = secrets[index]
	local reason = reasons[index]
	print (name, 'is hiding', secret, 'because', reason)
end

could be:

local peoples = { 'joe', 'jogn', 'gfajkg' }
local secrets = { 'agag', 'gafggf', 'gagfdg' }
local reasons = { 'sometyhing', 'another thing', 'ffszdgsg' }

for name, secret, reason in zip(peoples, secrets, reasons) do
	print (name, 'is hiding', secret, 'because', reason)
end

2 comments

0

Quick question, why are you using different tables and not a dictionary?

0

to show what i mean, this is just an example

2 answers

✓ Accepted answer
local ArbitraryArrayA = {1}
local ArbitraryArrayB = {2}
local ArbitraryArrayC = {3}


local function CollectAttributesFromIndex(Index, Tables)
	local Attributes = {}
	---------------
	for _, Attribute in ipairs(Tables) do
		table.insert(Attributes, Attribute[Index])
	end
	---------------
	return Attributes
end

local function ZipIteratorFactory(...)
	local Tables = {...}
	local Index = 0
	---------------
	return function()
		Index += 1
		---------------
		return unpack(CollectAttributesFromIndex(Index, Tables))
	end
end


for A, B, C in ZipIteratorFactory(ArbitraryArrayA, ArbitraryArrayB, ArbitraryArrayC) do
	print(A, B, C)
end

2 comments

0

thanks!

0

Note: This code is not designed to support uneven Tables.

No, but you can write your own

local function zip(First, Second, Third)
	local Index = 0
	
	return function()
		Index += 1
		
		local NextFirst = First[Index]
		local NextSecond = Second[Index]
		local NextThird = Third[Index]
		
		if not NextFirst or not NextSecond or not NextFirst then
			return nil
		end
		
		return NextFirst, NextSecond, NextThird
	end
end

local peoples = { 'joe', 'jogn', 'gfajkg' }
local secrets = { 'agag', 'gafggf', 'gagfdg' }
local reasons = { 'sometyhing', 'another thing', 'ffszdgsg' }

for name, secret, reason in zip(peoples, secrets, reasons) do
	print (name, 'is hiding', secret, 'because', reason)
end

the way this works is that zip returns a function which is being called every iteration, in the function i increment the index by 1 every time to create a loop, then it returns elements from each table with given index, if at least one of the elements is nil it breaks the loop.

I am not a pythoneer so i am not sure if this is how the function is supposed to work but i think it fits your example. You can adjust it how you need, i made it simple so you can understand it.

1 comment

0

works pretty good. thx

This discussion is preserved as it was. New answers, comments, and votes are closed.