Table Registering Last Object

I’ve seen a couple of other posts about this issue, but the solutions aren’t seeming to work for me. All of the posts I’ve seen are saying that it’s registering the last object in the table because all of the keys are the same. I’m not sure that’s the case here though. Here’s my code.

CustomButtons = {
	["One Day"] = 0.7;
	["Three Days"] = 0.7;
	["Five Days"] = 0.7; --0.7 is the transparency the button is going to be
	["Permanent"] = 0.7;
	["sub"] = 0.3;
}

function checkButton(name)
	for i,v in pairs(CustomButtons) do
		print(i.." "..v)
		if i == name then
			return v
		end
		return false
	end
end

Error:
image

If anyone had any information as to how I could fix this, a reply would be appreciated.

Tell me if I’ve interpreted what you want the code to do right.
The checkButton() function is supposed to return the value in the CustomButtons table.
So for example checkButton(“One Day”) should return 0.7. Yet it is currently returning false.

Correct. Some of the buttons in my UI are set to a different background transparency than others, so I needed to specify which ones weren’t normal, and what I want their background transparency to be.

Alright, smashing.

First let’s look at that code segment.

function checkButton(name)
	for i,v in pairs(CustomButtons) do
		print(i.." "..v)
		if i == name then
			return v
		end
		return false --Exits prematurely 
	end
end

You see the return false, its inside the for loop, and therefore only the first value in the table will be checked. Just move that outside to for loop and your in business.

function checkButton(name)
	for i,v in pairs(CustomButtons) do
		print(i.." "..v)
		if i == name then
			return v
		end
	end
	return false --Exits after all the values in the table have been checked
end

However before you use this fix, I’d like to introduce you to a cleaner solution. That of using string keys. Lua lets you access values in your table by a string key. So we don’t even need to iterate through the table. Just directly access the key.

function checkButton(name)
	if CustomButtons[name] == nil then
          return false
    end
	return CustomButtons[name]
end

With no need to iterate through the table, the code is cleaner, and more performance friendly.

1 Like

Thanks. I thought that I had put it outside of the loop already, but I guess I just wasn’t looking closely enough.