SUB


sub( string, first, [last] )
string the string that you want to convert into a table
first the number of characters from the beginning of the string to start pulling as the substring.

*If not given, the full string is returned.
last (optional) the number of characters from the beginning of the string to stop pulling as the substring. (default: full length of string) 

The sub( string ) function is used to separate a part of a string into a smaller string. The first character of the string is 1. 



For example, if we call sub("hello world"), the function will return a character or string from within the full given string.

string = "hello world"
print( sub( string,1 ) )   -- "hello world"
print( sub( string,2 ) )   -- "ello world"
print( sub( string,4,8 ) ) -- "lo wo"
print( sub( string,7,7 ) ) -- "w"

It is also possible to use negative numbers as the first and last arguments. This will count backwards from the end of the string. The last character in the string is -1. However, the substring will only return letters after first, so if you try to get characters from -3 to -6, you must order it from left to right (-6, -3).

string = "hello world"
print( sub( string,-1 ) )      -- "d"
print( sub( string,-3,-6 ) )   -- "" (empty string)
print( sub( string,-5,-1 ) )   -- "world"

Shorthand

If you only want a single character from the string, you can simply use  string[position] where string is the variable name of your string and position is the number of the character's index in the string:

string = "abcdefghij"
position = 4

print( string[position] )  -- "d"


Common Uses


The most common usage of the function sub() is to create a text appearance animation as if it is being typed out one character at a time. Example:

string = "hello world"
first = 1
last = 1


function _draw()
	cls()
	last+=.5	
	print( sub(string,first,last) )
end


Another way to reveal text is to use the clip() function. See the tutorial Text Wipe for a detailed example.

Images in this Guide by NerdyTeachers is licensed under CC BY-SA 4.0

832

24 May 2024

Font