Type error: function 'string.len' expects 'string' at argument '0' and got 'never'

Trying to get the length of a string to be able to use sub to extract data from it.
The string value is ‘Ores[25]’
Code is shown with error message in screenshot:


Can someone help me as I think the syntax is good.

3 Likes

Check in your Beta Features whether “New Luau Type Solver” is enabled, it has a lot of bugs. Usually what never means, is that you’re trying to refine one set of types to another set that is impossible to cast to, such as:

local n: any = nil

if typeof(n) == "string" then
	if typeof(n) == "number" then
		print(math.max(n, 0))
	end
end

image

n becomes never, because it is impossible for typeof(n) to be both string and number.


Here are some extra comments on the code in your screenshot:

  • Why are you using string.len? The # operator can be used instead:
local MyString = "Hello, World!"

-- > "13"
print(string.len(MyString))
-- > Also "13", but faster to write and understand
print(#MyString)
  • Why statName.sub(statName,1,4)?
local MyString = "Hello, World!"

-- > "Hell"
print(MyString.sub(MyString, 1, 4))
-- > Also "Hell", but runs slightly faster and faster to type
print(MyString:sub(1, 4))
-- > Finally, also "Hell", but the fastest out of all to execute
print(string.sub(MyString, 1, 4))
  • sessionData[playerKey]["Ores"][OresIndex] can be shortened to sessionData[playerKey].Ores[OresIndex]
  • You can also put sessionData[playerKey] in a variable, and I don’t think sessionData is a good variable name. It should probably be something like playerSessions instead, to better represent what it is, if I’m understanding your code correctly
1 Like

It was the Beta Feature New Luau Type Solver setting that was the problem. I had forgotten I had it set.
Thanks for the hints about using # instead of len and putting this in variable to make the code reading clearer and the naming of variables.
I did not include player in the sessionData variable as the script name contains Player in it.
I forgot about making the code so snippets are easy to understand when issolated from its parent.
All is working fine now.

2 Likes