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

How do you count characters in a string?

Started by HeroCC, 10 November 2014 - 10:15 PM
HeroCC #1
Posted 10 November 2014 - 11:15 PM
Hello! I am trying to count the amount of characters in a string that I get, and if it is above 17 (monitor limit) then it creates a new variable and prints both to the monitor.

My Current Code:
Spoiler

--API Loading
os.unloadAPI("sensors")
os.loadAPI("/rom/apis/sensors")
--Setup Monitor
mon = peripheral.wrap('top')
mon.setCursorPos(1,1)
mon.clear()
mon.setTextScale(1)
--Parse CommandLine Args
local args = {...}
local msg = args[1]
--Define MSG
if not msg then
		msg = ('Hello, World!')
	end

--Print!
mon.write(msg)

Is there any way to do this? Thanks!
shult #2
Posted 11 November 2014 - 12:08 AM
string.len(str)
will return the length of str. Note that in your script, args[1] refers to the second word in the command line arguments (because lua tables are zero-based), not the entire input.
Anavrins #3
Posted 11 November 2014 - 12:34 AM
All of the following will give you the lenght of a string

local msg = "Hello"  #-- 5 letter word
string.len(msg)
msg:len()
#msg
They will all return 5
Edited on 10 November 2014 - 11:36 PM
theoriginalbit #4
Posted 11 November 2014 - 12:39 AM
Note that in your script, args[1] refers to the second word in the command line arguments (because lua tables are zero-based), not the entire input.
This is incorrect, indexes start in Lua at 1, not 0, unless you specifically specify like so

local t = {
  [0] = "zero-index",
  "index one",
  "index two",
}