ID:1762120
 
(See the best response by Kaiochao.)
Code:
n/A


How to return a list of characters. For example, I have a text file I want to convert to a list of all its character.

var/A = "1111"


My question is to return a list like so:

var/list/B = list("1","1","1","1")


This is easy in python, but I can't seem to figure out how to do this in BYOND XD
You'd have to iterate over every character and manually append it to the list.

            var
string = "Hello world!"
list/return_list = list()

for(var/pos = 1,pos <= length(string),pos++)
var/character = copytext(string,pos,pos+1)
return_list += character

src << "The list contains [return_list.len] character\s!"
for(var/C in return_list)
src << "[C]"


Keep in mind that operations like this on larger strings will be slow, and very resource-demanding, especially if you don't sleep() out the loop. If you're planning on loading entire files with it you're gonna end up with a fairly long-winded process that generates a fairly massive list.
The BYOND proc for getting a character at position X in string Y is "copytext((Y),(X),(X)+1)". The proc for converting a file to a string is file2text(file).

With those 2, you can easily set up a for-loop to copy each character in the file to a list.

And yes, string and file handling is very lacking in BYOND. One of the things i'm working on addressing in a current project. For example, the above copytext() operation is aliased as GetChar(X,Y).
Best response
#define getchar(string, index) ascii2text(text2ascii(string, index))

I'm not sure how it compares to copytext(string, index, index+1), but that's another way.

So,
proc/getchars(string)
var result[length(string)] // preallocate space for speed
for(var/i in 1 to result.len) result[i] = getchar(string, i)
return result
The problem with ascii2text/text2ascii is that they probably won't work with utf-8, which afaik BYOND otherwise supports.
It will work as UTF-8 uses the 7-bit US-ASCII specification, so all ASCII messages will be represented with no changes.
As long as the character passed is in this table, you are good to go: