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

[Question] How to get a specific character in strings?

Started by jerry242, 12 March 2012 - 01:46 PM
jerry242 #1
Posted 12 March 2012 - 02:46 PM
I wonder how you can find a character in a string.


exampleString = "Example"
a = 3
function getChar(a) -- a is the place to look for character(Here it should return a)
  char = magic.getChar(a) -- Any command that does this?
  return char
end

Is there any way to do this?
Any help appreciated :mellow:/>/>
Sebra #2
Posted 12 March 2012 - 03:05 PM
string.sub (s, i [, j])
Returns the substring of s that starts at i and continues until j; i and j can be negative. If j is absent, then it is assumed to be equal to -1 (which is the same as the string length). In particular, the call string.sub(s,1,j) returns a prefix of s with length j, and string.sub(s, -i) returns a suffix of s with length i
So you need
char = string.sub(exampleString,a,a)
Hawk777 #3
Posted 12 March 2012 - 03:23 PM
Be aware of this bug if using string.sub: http://www.computercraft.info/forums2/index.php?/topic/27-stringfind-twice-bugged/
jerry242 #4
Posted 12 March 2012 - 03:54 PM
Thanks! :mellow:/>/>
Espen #5
Posted 12 March 2012 - 09:48 PM
Be aware of this bug if using string.sub: http://www.computerc...d-twice-bugged/
But wasn't string.find() the function that was bugged?
Or does string.sub() somehow make use of string.find() internally?
I'm just asking because I did have buggy behaviour with string.find(), but never with string.sub().
Hawk777 #6
Posted 13 March 2012 - 04:44 AM
The bug is the combination thereof. Technically the bug is in string.find, but you can only experience it if you call string.find on a string that was constructed by means of string.sub. So the bug is worth mentioning anywhere someone suggests using string.sub, because one of the things you might reasonably do with the result is call string.find on it, and also because the most convenient place to fix the bug is at the point of calling string.sub, by just concatenating the empty string onto the return value.
Espen #7
Posted 13 March 2012 - 11:05 AM
Alright, good to know, thx for clarification. :mellow:/>/>