Log In  

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
P#10004 2015-04-19 13:02 ( Edited 2016-06-01 07:51)

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?

P#21557 2016-05-28 16:51 ( Edited 2016-05-28 20:51)

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]

P#21559 2016-05-28 17:02 ( Edited 2016-05-28 21:02)

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!

P#21560 2016-05-28 17:24 ( Edited 2016-05-28 21:25)

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.

P#21562 2016-05-28 18:04 ( Edited 2016-05-28 22:07)

Ah, that sub is what I was looking for, thanks a lot, very helpful!

P#22017 2016-06-01 03:51 ( Edited 2016-06-01 07:51)

[Please log in to post a comment]

Follow Lexaloffle:          
Generated 2024-03-29 10:32:08 | 0.007s | Q:17