So i am wondering why Lua strings don’t. Of course I could use the # operator but strings are immutable so I don’t see the point in an operator for strings
They’re both the same function. When you use :len() you are calling it as a method of a particular string object. (sort of like passing the string as a ‘self’ argument)
@Blokav@FastKnight401 a function call to get a strings length is pointless. The length of a string will never change so I shouldn’t have to use an operator or a function for something that is constant
This is true for strings you make and store in scripts, but if the user made the string and you need to find the length, then you would have to use an operator.
I guess it’s just the way strings are implemented. I do know that in other languages (e.g. Java) strings do have a length property as well as a length method, the latter of which most posts above describe, but I don’t think there’s any real reason for that. Want to ask Roberto Ierusalimschy?
Fascinating page I came across while searching, though this is just length functions and probably not relevant at all:
Because it doesn’t. I think the only reason the Lua developers didn’t add it was because they didn’t think it would be a good contribution.
Just because I’m bored though…
If you some how unlock the string metatable you could do this where you overwrite the __index method of the default string metatable. (Yes this works for anyone wondering, just run the code in an unsandboxed lua environment like https://www.lua.org/demo.html)
local stringMetatable = getmetatable("")
local oldIndex = stringMetatable.__index
function stringMetatable:__index(index)
if index == "length" then
return #self
end
return oldIndex[index]
end
Or in a more plausible (and equally dumb) case you could wrap your string objects in a table or userdata.
local String = {}
do
--// String Class Methods
local stringMethods = {
__metatable = "Sorry I am locked!!"
}
stringMethods.__index = stringMethods
function String.new(string)
local newString = {
length = #string,
value = string
}
setmetatable(newString, stringMethods)
return newString
end
end
local testString = String.new("hello world")
print(testString.length)
However all of this is silly and you should just use the string::len function.