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

Is there a way to condense this code?

Asked by
RedCombee 585 Moderation Voter
7 years ago

I'm creating a multiplayer game that allows multiple characters to be controlled by the same keyboard (Super Smash Brothers, essentially). As a result, I have the same set of variables for each character, and my code looks like this:

player1 = {
    idle = true;
    jumping = false;
    -- Et cetera
}

player2 = {
    idle = true;
    jumping = false;
    -- You get the idea, hopefully.
}

How might I be able to create the same effect without taking up a ton of script space? I would assume that for loops are the way to go, but is there any other way of doing it?

2 answers

Log in to vote
5
Answered by
Link150 1355 Badge of Merit Moderation Voter
7 years ago
Edited 7 years ago

You could do like gskw said or also do

local table1 = { 2, 1 }
local table2 = { unpack(table1) }

which is essentially the same thing but stands in a single line.

Note however that if table1 contains non-numerical indexes, they will be lost.

Ad
Log in to vote
3
Answered by
gskw 1046 Moderation Voter
7 years ago

You can do this using a very basic for loop, i.e.

local table1 = {a = 2, b =1};
local table2 = {};

for key, val in next, table1 do -- For every key in table 1
    table2[key] = val; -- Copy the key-value pair over to table 2
end
0
Can you not just do table2 = table1? Same effect but doesn't need to loop through every value? Uglypoe 557 — 7y
2
That would make table2 a reference to table1 and not a copy. 1waffle1 2908 — 7y

Answer this question