I've been trying to use the string.len and string.sub functions to iterate over each character in a string. Unfortunately they need the string library which doesn't seem to be recognised.
So is there an equivalent way of doing this?
for i=1,text.length do print(text[i]) end |
I too would love to use string fuctions such as picking character x of a string or converting integers to characters (for names in highscores using dset/dget). Any chance to get such?
In Lua the '#' operator gives you the length of something (strings, arrays, and objects with a length metamethod). So to get the last character you can just do: text[#text]
Using string [#string] in Pico gives me an error. But you brought me to an idea: i could fill a subtable with 26 pairs of an integer and a character and save the highscore names as integers pointing to the characters using that table. Thanks!
To get the length of the string, use the # operator on the string.
local s = 'Hello' print(#s) -- 5 |
sub(s, i, j) will return a substring of s using the range i .. j that you specify. If you omit the last argument, then it defaults to #s.
local s = 'Hello' local i = 1 local j = 3 print("'" .. sub(s, i, j) .. "'") -- Hel print("'" .. sub(s, i, i) .. "'") -- H print("'" .. sub(s, i) .. "'") -- ello |
Note that there is no individual character indexing on strings, just like in Lua, so you can't use the indexing operator [] to read a single character. Instead, you need to get a substring to get a string of length 1 if you want individual characters (using sub in pico8, string.sub in Lua). So use sub(s, i, i) to do that.
If you want the character code for a character, unfortunately there's no built-in way to do that right now (so no equivalent to string.char / string.byte from Lua). You will need to write a character code lookup table to turn single-character strings into numeric codes. This post by YellowAfterLife explains how you can do this.
Ah, that sub is what I was looking for, thanks a lot, very helpful!
[Please log in to post a comment]