This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Cloud Ninja's profile picture

Having trouble getting a strings length and storing it as a variable

Started by Cloud Ninja, 02 May 2015 - 04:12 PM
Cloud Ninja #1
Posted 02 May 2015 - 06:12 PM
So i have code like this


A = read()
string = A
return string:len()
And i can print it out very easily by replacing string:len() with print(string:len())

But how can i store the length in a variable and then do what i need with the variable?
LBPHacker #2
Posted 02 May 2015 - 08:20 PM
Just assign it to a new variable:
length = yourstring:len()

You'll want to avoid naming your variables string though. string is a global table which you might want to use in the future. I realize you're using the colon notation, but still, unintentionally overwriting global tables is never good.
len = yourstring:len()       -- this is equivalent to
len = string.len(yourstring) -- this

And of course you might want to declare your variables locally so they won't clutter the global environment:
local len = yourstring:len()

There's still more. string.len is sort of old and to be honest, I didn't even know it existed. I recommend using the # (length) operator instead:
len = yourstring:len()       -- all of
len = string.len(yourstring) -- these
len = #yourstring            -- do the same
Edited on 02 May 2015 - 06:25 PM
Cloud Ninja #3
Posted 03 May 2015 - 12:32 AM
so if i declare

A = "Hello World"
--can i do
B = #A
flaghacker #4
Posted 03 May 2015 - 06:01 AM
so if i declare

A = "Hello World"
--can i do
B = #A

Yes.