Can someone explain to me why you can "index strings"

I ran into an error that was caused by mixing up two variables, String, which is a string, and Strings a table. Instead of indexing Strings (the table) I indexed String (the string), which lead to the error “Attempted to index nil with string”
I never realized I was trying to index a string, until I got an AI to figure it out for me… I assumed it was a table since it was getting indexed and returned nil

However, WHY DOES INDEXING A STRING NOT ERROR???

Well, I would understand if you could index a string and get the character at that position in the string, but that isn’t the case, it just returns nil, which leads to more confusion when running into errors like mine

I found this thread while searching, and from the solution, it seems like this is a totally normal behaviour, which is even more confusing for me

(You also have to index a string variable, or use parenthesis, indexing a string directly will error)

local s = "a" 
print(s[1]) --> nil
print("a"[1]) --> Expected ')' (to close '(' at column 20), got '['
print(("a")[1]) --> nil
1 Like

you can index most types, no clue why

1 Like

What types exactly?

I tried with numbers, booleans, nil, and those don’t work, giving you the traditional “Attempted to index ‘type’ with number”

As for roblox types, they are objects, so you can index their properties, which makes sense

1 Like

idk what i meant by most but yeah it doesnt make sense

its an issue in Lua itself, not Roblox. i tested it here

Isn’t String a table ? When you do String.sub() or any other function it’s like when you index a table with . instead of [] ?
I haven’t tested but maybe you can do String["sub"]()

I’m really not sure about that it just a theory

1 Like

That’s probably it, I forgot about that feature of strings

local String = "Hello world"
print(String["reverse"]("Bruh")) --> hurB

This is so cursed lol

What a weird design decision

that happens bc strings is a array (table) of chars each char being 1 byte and it make sense if you thought about that is how the computers handle strings (char array/table of chars) in general

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.