Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

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

Asked by
0hsa 193
4 years ago
Edited 4 years ago

something like this:

1local peoples = { 'joe', 'jogn', 'gfajkg' }
2local secrets = { 'agag', 'gafggf', 'gagfdg' }
3local reasons = { 'sometyhing', 'another thing', 'ffszdgsg' }
4 
5for index, name in next, peoples do
6    local secret = secrets[index]
7    local reason = reasons[index]
8    print (name, 'is hiding', secret, 'because', reason)
9end

could be:

1local peoples = { 'joe', 'jogn', 'gfajkg' }
2local secrets = { 'agag', 'gafggf', 'gagfdg' }
3local reasons = { 'sometyhing', 'another thing', 'ffszdgsg' }
4 
5for name, secret, reason in zip(peoples, secrets, reasons) do
6    print (name, 'is hiding', secret, 'because', reason)
7end
0
Quick question, why are you using different tables and not a dictionary? MineBlox_Artz 65 — 4y
0
to show what i mean, this is just an example 0hsa 193 — 4y

2 answers

Log in to vote
2
Answered by
Ziffixture 6913 Moderation Voter Community Moderator
4 years ago
Edited 4 years ago
01local ArbitraryArrayA = {1}
02local ArbitraryArrayB = {2}
03local ArbitraryArrayC = {3}
04 
05 
06local function CollectAttributesFromIndex(Index, Tables)
07    local Attributes = {}
08    ---------------
09    for _, Attribute in ipairs(Tables) do
10        table.insert(Attributes, Attribute[Index])
11    end
12    ---------------
13    return Attributes
14end
15 
View all 30 lines...
0
thanks! 0hsa 193 — 4y
0
Note: This code is not designed to support uneven Tables. Ziffixture 6913 — 4y
Ad
Log in to vote
1
Answered by
imKirda 4491 Moderation Voter Community Moderator
4 years ago
Edited 4 years ago

No, but you can write your own

01local function zip(First, Second, Third)
02    local Index = 0
03 
04    return function()
05        Index += 1
06 
07        local NextFirst = First[Index]
08        local NextSecond = Second[Index]
09        local NextThird = Third[Index]
10 
11        if not NextFirst or not NextSecond or not NextFirst then
12            return nil
13        end
14 
15        return NextFirst, NextSecond, NextThird
View all 25 lines...

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.

0
works pretty good. thx 0hsa 193 — 4y

Answer this question