Jump to content




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


  • You cannot reply to this topic
3 replies to this topic

#1 Cloud Ninja

  • Members
  • 361 posts

Posted 02 May 2015 - 05: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?

#2 LBPHacker

  • Members
  • 766 posts
  • LocationBudapest, Hungary

Posted 02 May 2015 - 07: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 by LBPHacker, 02 May 2015 - 07:25 PM.


#3 Cloud Ninja

  • Members
  • 361 posts

Posted 02 May 2015 - 11:32 PM

so if i declare
A = "Hello World"
--can i do
B = #A


#4 flaghacker

  • Members
  • 655 posts

Posted 03 May 2015 - 05:01 AM

View PostCloudNinja, on 02 May 2015 - 11:32 PM, said:

so if i declare
A = "Hello World"
--can i do
B = #A

Yes.





2 user(s) are reading this topic

0 members, 2 guests, 0 anonymous users