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

Getting the Length of A String

Started by ebernerd, 19 August 2014 - 04:07 AM
ebernerd #1
Posted 19 August 2014 - 06:07 AM
I am programming a custom API for my upcoming project, and a lot of it requires me to get the length of a string.

What is the simplest way possible to do this?

EDIT: Got it. It would be…

string.len(string)
Edited on 19 August 2014 - 04:22 AM
Dragon53535 #2
Posted 19 August 2014 - 06:23 AM
local string = "random string"
print(#string) --> 13
There are a couple of easy ways to get the length of a string, one being what i just did, and the other being

local lengths = string.len("somestring")
print(lengths) --> 10
string.len() is basic lua string manipulation, however i believe that having 0's in your string will not count off towards the end goal (this was read from the lua 5.1 manual). However using the length modifier, #, does include 0's

Edit: I got ninja'd by OP… D:
Edited on 19 August 2014 - 04:28 AM
theoriginalbit #3
Posted 19 August 2014 - 09:36 AM
string.len() is basic lua string manipulation, however i believe that having 0's in your string will not count off towards the end goal (this was read from the lua 5.1 manual).
nope, having a 0 in the string doesn't cause an effect on string.len
Dragon53535 #4
Posted 19 August 2014 - 05:33 PM
Well then the lua 5.1 manual was wrong D: anyways i believe he found his solution before i posted.
theoriginalbit #5
Posted 20 August 2014 - 03:23 AM
Well then the lua 5.1 manual was wrong
The thing you have to understand is while ComputerCraft has Lua 5.1 it is running LuaJ, an implementation of Lua — which is normally in C — in Java; this means that it doesn't have the same set of features due to the differences between C and Java. LuaJ even introduces bugs that Lua does not.
Edited on 20 August 2014 - 01:23 AM
Bomb Bloke #6
Posted 20 August 2014 - 03:35 AM
Beats me what you guys are on about.

The Lua 5.1 reference manual states:

string.len (s)
Receives a string and returns its length. The empty string "" has length 0. Embedded zeros are counted, so "a\000bc\000" has length 5.

Note the escape character in front of the triple 0s. They end up representing ASCII code 0, often referred to as a null, which in many languages is used to mark the end of a string (but not in Lua, apparently). Compare this to the character "0", which is ASCII code 48 and quite unrelated to what the manual is talking about.

If two implementations of Lua are written in different languages it does not justify them functioning in different manners. Sure, it might be a reason as to why they do, but only when coupled with "laziness on behalf of the implementing programmer".