Seems like a common request for functions to convert to and from char codes.
Time will show whether it shall be added to the program, but until then you can do it by yourself:
Initialization (59 tokens, 197 bytes):
chars=" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" -- ' s2c={} c2s={} for i=1,95 do c=i+31 s=sub(chars,i,i) c2s[c]=s s2c[s]=c end |
(the blank comment is there solely to keep the editor from glitching out due to lack of escape sequence support)
After this is executed, you'll find yourself with having two tables - s2c, holding char->code pairs, and c2s, holding code->char pairs.
Since using these directly can be slightly less comfortable, here are a couple helper functions:
chr(code) : Returns the char (string) for the given code [13tk\36b]:
function chr(i) return c2s[i] end |
Example: chr(33) == "!"
ord(string, pos) : Returns the code for the character at the given position (optional argument) in a string [26tk\57b]:
function ord(s,i) return s2c[sub(s,i or 1,i or 1)] end |
Example: ord("Hello!", 6) == 33
chrs(...codes) : Forms a string from one or more codes [50tk\103b]
function chrs(...) local t={...} local r="" for i=1,#t do r=r..c2s[t[i]] end return r end |
Example: chrs(104,105,33) == "hi!"
Additional notes:
- If you are in a dire need, you can shorten the chars-string to only include the uppercase letters.
- Depending on situation, you may also want this to handle linebreak via
s2c["\n"]=10 c2s[10]="\n" |
Then you can use the multiline string format [[ text ]]... which currently isn't considered as a string for token count though.
Have fun!
This could be the start of a code archive?
Useful functions shared between us all.
Here's one from me based on https://en.wikipedia.org/wiki/Fisher–Yates_shuffle
function shuffle(t) -- Fisher-Yates Shuffle local n = #t while n >= 2 do local k = flr(rnd(n)+1) t[n], t[k] = t[k], t[n] n = n - 1 end return t end |
matt, how about github repo with useful Pico code? I wouldn't have time to maintain one so I can't make it, but someone should imo!
[Please log in to post a comment]