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

Iterating through a table?

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

1 comment

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.

1 answer

✓ Accepted answer

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)

5 comments

0

It has an underline in blue on 'level' on line 10

0

I assumed you had a global variable called "level" since it didn't refer to anything.

0

No, level is suppose the be the level inside the table

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.

0

I've never worked with tables like this before

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