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

Iterating through a table?

Asked by 7 years ago
local guns = {"Starter", "Rifle"}

local gunVariables = {
    {
        cost = 0,
        level = 5
    },
    {
        cost = 200,
        level = 5
    }
}

chosenClass.Changed:connect(function(newClass)
    gunLabel.Text = newClass
    for i, v in pairs(guns) do
        if v == newClass then
            for n, k in pairs(gunVariables[i]) do
                print(n, k)
                if n == level then
                    print(n, k)
                    levelLabel.Level.Text = k
                end
            end
        end
    end
end)

I'm trying to iterate through the table of values. Each gun has its own level and cost. How can I get that to work in my code. I have if n == level then to make sure it's got the right variable in the table, but it's not working. Please help

0
It should be if n == 'level'; the script editor gives you a warning about this in the form of a blue underline, as well. Pyrondon 2089 — 7y

1 answer

Log in to vote
1
Answered by
cabbler 1942 Moderation Voter
7 years ago
Edited 7 years ago

You should look into using a dictionary as well as better conventions. Regardless, when you do

for n, k in pairs(gunVariables[i]) do
    print(n, k)
    if n == level then

First, level should be a string, as the dictionary key is a string. Roblox only allows you to init the key without quotes for convenience. wiki Secondly You loop through gunVariables table in the order cost,level. So you should check if k == 'level' rather than n. Most importantly since you know the order there is no reason to do this check in the first place.

Here's what I recommend your script looks like:

local guns = {
    Starter = {cost=0, level=5},
    Rifle = {cost=200, level=5}
}

chosenClass.Changed:connect(function(newClass)
    gunLabel.Text = newClass
    local gunVars = guns[newClass]
    local cost, lvl = gunVars.cost, gunVars.level
    levelLabel.Level.Text = lvl
end)
0
It has an underline in blue on 'level' on line 10 NinjoOnline 1146 — 7y
0
I assumed you had a global variable called "level" since it didn't refer to anything. cabbler 1942 — 7y
0
No, level is suppose the be the level inside the table NinjoOnline 1146 — 7y
0
Sorry I thought you were more advanced. There is no need to check whether the index is equal to "level" and I will edit the post accordingly. cabbler 1942 — 7y
0
I've never worked with tables like this before NinjoOnline 1146 — 7y
Ad

Answer this question