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

If statements, and for loop not working. Why?

Hey guys, there is a problem that happend when I scripted. There came a error when it was happening. Here's the code

local tabletest = {"cheese", "chicken", false, 3}

for i, v in pairs(tabletest:GetChildren()) do

if tabletest[1] == "cheese" then
elseif
tabletest[2] == "chicken" then
elseif
tabletest[3] == false then
elseif 
tabletest[4] == 3 then
print([1] or [2] or [3] or [4])
end

end

In my output, I got a message saying Host:13: Expected identifier when parsing expression, got '['

What have I done wrong?

2 answers

On line 12(13) you say, print([1] or [2] or [3] or [4]), just saying [4] for example is not enough information, you even use this yourself earlier on on line 5(6). Just use:

print(tabletest[1] or tabletest[2] or tabletest[3] or tabletest[4])

Another thing to point out is that or searches for a true value (or an existent one), not what you have done, you have already done this in your if statements but haven't executed them. Do this:

local tabletest = {"cheese", "chicken", false, 3}

for i, v in pairs(tabletest:GetChildren()) do

if tabletest[1] == "cheese" then
print(tabletest[1])
elseif tabletest[2] == "chicken" then
print(tabletest[2])
elseif tabletest[3] == false then
print(tabletest[3])
elseif tabletest[4] == 3 then
print(tabletest[4])
end
end

2 comments

0

When I did that, I got another error in the output saying "Runtime error in InCommand script: Host:4: attempt to call a nil value"

0

idk

GetChildren is a method of the Instance base-class. You're attempting to perform a key-value pairs enumeration, which requires an array, that of which is already stored at raw in your variable tabletest.

The compiler isn't able to comprehend what you mean by [#], as you're essentially just encapsulating a practically random number in square-braces, which will result in a Syntax Error.

To successfully index an element within an array, you must follow this format: tableName[index]

Lastly, I cannot stress enough how poor a practice it is, to individually evaluate each attribute the way you have done so. You can easily build a linear array to compare each potential value for convenience:


local arbitraryTable = {"Hello world!", "Jeff-the-sheep", 2020, false}

local expectedTableMatches = {"Hello world!", "Notch", 2021, false}


for _, attribute in pairs(arbitraryTable) do
	---------------
	for _, attributeMatch in pairs(expectedTableMatches) do
		---------------
		if (attribute == attributeMatch) then
			print(attribute)
		end
	end
end


--[[ Output:

	'Hello world!'
	false
]]

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