SPLIT


split( string, [separator], [convert numbers] )
string the string that you want to convert into a table
separator (optional) the symbol to split the string by (default: comma ",")
convert numbers (optional) a boolean. True will convert numbers in the string to an actual number type of variable. False will leave any numbers in the strings as strings. (default: true)

The split( string ) function is used to separate a string into a table of elements, separated by commas or the given separator character. It will attempt to convert any digits in the string into number variables unless the third argument is given as false.



For example, if we call split("a,b,c,d"), the function will return a table that has four entries with the values of each letter between the commas.

table = split("a,b,c,d")
print( table[1] ) --"a"
print( table[2] ) --"b"
print( table[3] ) --"c"
print( table[4] ) --"d"

To use a different separator and maintain the commas in your table entries, you can include the separator argument. For example, a common alternative is to use the pipe character "|" found above enter on QWERTY keyboards.

table = split("a,b,c,d|e,f,g,h", "|")
print( table[1] ) --"a,b,c,d"
print( table[2] ) --"e,f,g,h"

To leave individual number entries as strings instead of being converted, use the third argument. For example:

table = split("1,2,3,4") --default true
print( table[1] ) --1
print( table[2] ) --2
print( table[3] ) --3
print( table[4] ) --4

table = split("1,2,3,4", ",", false)
print( table[1] ) --"1"
print( table[2] ) --"2"
print( table[3] ) --"3"
print( table[4] ) --"4"


Common Uses

The most common usage of the function split() is to save tokens. Strings, no matter their length, cost only 1 token. But creating tables and their entries, can cost many tokens. Example:

colors = {8,9,10,11,12,13,14}
--10 tokens

colors = split("8,9,10,11,12,13,14")
--5 tokens

Advanced

Another way to save many tokens is to use split() with another function unpack() to set multiple variables from a single string. Example:

--single assignments
sprite=1
x=10
y=20
w=1
h=1
speed=2
jump=6
atk=10
def=5
--27 tokens

--multiple assignments
sprite,x,y,w,h,speed,jump,atk,def=
1,10,20,1,1,2,6,10,5
--19 tokens

--split and unpack
sprite,x,y,w,h,speed,jump,atk,def=
unpack(split("1,10,20,1,1,2,6,10,5
")
--16 tokens

480

19 Aug 2023

Font