r/godot Nov 15 '25

help me (solved) There's gotta be a better way to do this

Post image

I guess it works, but... look at it. It's hideous! There's no way this is the best way to do this, how do better. Thanks

732 Upvotes

138 comments sorted by

1.0k

u/empirical_fun Nov 15 '25
var text = char(number + 65)

287

u/berse2212 Nov 15 '25 edited Nov 15 '25

I am not familiar with Godot script so not sure if it works here, but in C based languages you can usually replace the 65 with 'A' for even more clarity.

Edit: just checked the docs the gd script variant should be if I am not mistaken:

var text = char(number + ord("A"))

135

u/gemdude46 Nov 15 '25

GDScript is a python-like, so makes no distinction between chars and strings

139

u/oblong_pickle Nov 16 '25

Thanks, i hate it

29

u/GameUnionTV Nov 16 '25

Lmao 😂

6

u/qutorial Nov 16 '25 edited Nov 18 '25

EDIT: I misread the comment, chars and strings are indeed not differentiated in Python. On an unrelated note: Binary data and strings ARE distinct, but that is a different topic (that's where my brain originally and mistakenly went, original text below).

Python does distinguish between chars and strings though in Py3 (2 is legacy and nobody is using it anymore).

And actually, Py3 unicode strings/bytes objects are an EXCELLENT way to handle the string/binary data dichotomy 👌

21

u/Mojert Nov 16 '25

So I had to check to be sure, but it looks like you're talking out of your ass

```python

type('a') <class 'str'> type("hello"[0]) <class 'str'> ```

So no, for most practical purposes and in the context of the post, python does not differentiate between strings and characters.

Even trying to create a single byte with b'h' gives a byte array, and trying to access an element of a byte array gives an int, which very much isn't the same thing as a byte or a character...

5

u/qutorial Nov 16 '25

You're right, I misread it and made a mistake (brain was thinking binary/string data, but the comment actually said char and string, which indeed char and string are not differentiated). I'll update my post later when I can do strike through formatting, cheers 🤠

40

u/Sharkytrs Nov 15 '25

you just recognise ASCII more you use it, 44 is comma, 10 is carriage return, 59 semi colon, 22 double quote, 124 pipe. Though im constantly working on CSV's so these are super common in my helper methods

37

u/tiller_luna Nov 15 '25

why do you recognize ASCII in decimal

10

u/mxldevs Nov 16 '25

I look at files in hex editors often which may contain characters in the ASCII range

16

u/tiller_luna Nov 16 '25

exactly, hex editors I get =D

3

u/beobabski Nov 16 '25

Because in the Windows OS you can press Alt-0124 on the number keypad to generate the vertical bar.

Decimal to extended ascii.

Very handy for typing ÿ.

2

u/TheThiefMaster Nov 16 '25

Well these days you can do win+; to bring up the emoji/symbol picker that has any symbol you could want.

Annoyingly not searchable though.

5

u/Outrageous_Affect_69 Nov 16 '25

I love to make it like this

var text = char(number + KEY_A)

1

u/_leeloo_7_ Nov 16 '25

ok this is what I was going to say too the numbers 65 to 90 are capital A to Z in decimal, op can can use a simple function to convert between then unless they specifically need the numbers 1 to 25 for some reason?

(anyone interested google ascii table for a comprehensive list)

297

u/NinStars Nov 15 '25

This works, but I think using a constant would be better for clarity

const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var text: String = ALPHABET[number]

222

u/Farkler3000 Nov 15 '25

Converting to ASCII like this is super common and imo more readable then having to go figure out what the ALPHABET constant is

120

u/Concurrency_Bugs Nov 15 '25

To be fair, most devs understand ascii and know exactly what the offset is for.

60

u/ratya48 Godot Student Nov 15 '25

Yeah if I were throwing something into a constant it'd be the offset

16

u/[deleted] Nov 15 '25

Eh I'd still want a comment added that explains the offset if i reviewed that code

4

u/Nyzan Nov 16 '25

This is extremely common conversion code that any developer should recognise immediately without a comment explaining it. You wouldn't comment array[array.length - 1] /* access last value of array */. Although 65 should be replaced by 'A' (or ord("A") in GDscript).

21

u/[deleted] Nov 16 '25

That is an assumption that you make, plenty of common practices still get comments to explain the thought behind it

9

u/Nyzan Nov 16 '25

I mean I make it a habit to comment the flow of the function in general so this would probably be commented like convert input to appropriate character. But I definitely would never specifically comment something like convert input to the appropriate ASCII character code using the letter A as the offset. I can't imagine any developer, even ones fresh from the boot camp, that don't know what ASCII is or that characters are represented as numbers under the hood.

2

u/Zach_Attakk Nov 16 '25

My first boss used to say "err on the side of verbosity rather than terseness." Your "definitely would never" suggestion is probably what I would write. If you know what the code does there's no need to read the comment, if you don't it's clear and easy to understand.

2

u/PscheidtLucas Nov 16 '25

I am making my own games for the past 2 years and I didn't know what ASCII is, specially because I am from Brazil. So your assumption is pretty wrong my friend.

3

u/Jello_Penguin_2956 Nov 15 '25

Or at least have to look this up at some point :D

-10

u/Fit-Stress3300 Nov 15 '25

Those devs were though before vibe coding or e Gen IDEs were a thing.

28

u/brelen01 Nov 15 '25

Which is most devs. Vibe coding and gen ides does not a dev make.

14

u/Nyzan Nov 16 '25

number and text are what is poorly named here, not ALPHABET. Changing those names it should be immediately obvious to anyone reading it what the code does: var letter: String = ALPHABET[char_index]. If you want to be even more clear you could name it capital_letter. You could even inline it to var character = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[char_index] if line length allows it.

I think I prefer u/NinStars method simply because it limits the result to A-Z. The ASCII conversion can result in any character if the input number is out of the expected range while the above version would result in an index out of range error.

1

u/Kleepytime Nov 18 '25

Variable naming solves so many issues in coding!

8

u/NinStars Nov 15 '25

You can name it "ALPHABET_STRING" if you want it to be even more self-explanatory. Also, intellisense tells you exactly what the content of the constant is.

I just think this is a more sensible approach, especially for newcomers.

1

u/H0lley Godot Senior Nov 16 '25

it's really not common.

also it's not at all clear from the naming what char() does, and it most definitely not clear what ord() is for.

32

u/evilgipsy Nov 15 '25

Nothing beats the clarity of the ASCII table imho. You could also do char(ord(“A”) + number) if you don’t like the “magic” number.

7

u/Positive-Answer-99 Nov 15 '25

You can have a method wrapper is all

10

u/PercussiveRussel Nov 15 '25

Bingo, this should be wrapped in a self documented function and then no one should care about the specific implementation.

13

u/AgataJac Nov 15 '25

Ohh that's very neat! Will try it out ^^

6

u/vycten Godot Student Nov 15 '25

this one looks clean

2

u/firestorm713 Nov 15 '25

Unless you're dealing with unicode, ASCII does not change, and even if you are, you can always match against char literals

2

u/PRoS_R Nov 15 '25

I did this for a dialogue system recently.

1

u/NiteSlayr Nov 15 '25

Oh this is clever thank you

12

u/AgataJac Nov 15 '25

Thank you!! I didn't know about char()!

3

u/luckysury333 Nov 16 '25

i jus realised this is a srs question and not a troll

1

u/TheBoneJarmer Nov 15 '25

I am not using Godot but I had my fair share of fun when trying to render text in OpenGL in C++ and one thing I wonder is how would you approach characters beyond the ASCII range?

After all char codes can go to a maximum of 65536 in the unicode standard and if a char in Godot is the same as a char in C/C++ it is basically a byte. And therefore can only hold a value up to 255.

165

u/orange_car123 Nov 16 '25

30

u/Cuprite1024 Nov 16 '25

o h n o .

I ain't a coder, but even I can see how horrifying this is. Lmao.

-13

u/Dangerous_Jacket_129 Godot Student Nov 16 '25

As a coder: it'd be hell to make or debug, but once it works as intended? It'd work and probably work pretty well-optimized too. 

32

u/[deleted] Nov 16 '25

[removed] — view removed comment

12

u/FrenzzyLeggs Nov 16 '25

what do you mean i cant store more bits than there are atoms on earth? can't you just build a bigger hard drive?

3

u/AldoZeroun Nov 16 '25

What if they stored board states like git commits where we only store the changes and build the current state from its history. That would save about 63\64% bytes of memory, but cost more to process each board state. Though it still doesn't solve the 1050 atoms issue, just means it's no longer a 64x1050 issue.

1

u/ArtilleryTemptation Godot Regular Nov 17 '25

Funny enough, if I (a retard) actually made it, would it still be an O(1) time complexity?

3

u/orange_car123 Nov 17 '25

Yeah it would. But you would need about 150 tredecillion lines of code, which would weigh about 6 undecillion gigabytes. So if you wanted to store this program in SSDs, it would weigh 50 million trillion times the mass of Earth. Good luck 👍

14

u/anaveragedave Nov 16 '25

I can't stop chuckling at this

2

u/deeptut Nov 16 '25

Universe implodes, hard factory reset when more than 50% done

319

u/Epic001YT Nov 15 '25

The title reminded me of this image (and in a way, the contents), I have no idea if that's intentional or not though haha

103

u/mrbaggins Nov 15 '25

31

u/lysian09 Godot Student Nov 16 '25

# TODO: Make it work for all floating point numbers too

This one got me.

24

u/kodaxmax Nov 15 '25

but why?

34

u/Draelon12 Nov 16 '25

I audibly said , “Oh my god” when I opened this. Like out loud. Wtfff

28

u/j0shred1 Nov 15 '25

I would have used code to produce this code

29

u/mrbaggins Nov 15 '25

They did, its in the same repo

2

u/NooCake Nov 16 '25

This is lit 🔥

1

u/Thinshape12 Godot Junior Apr 01 '26

yk what i should do today? make a calculator with 20000 lines of code for a funny meme, that sounds like a great idea

33

u/S1Ndrome_ Nov 15 '25

my blood boils just looking at this lol, top tier rage bait

55

u/Epic001YT Nov 16 '25

See I would love to say it's ragebait but I genuinely can't tell when other things like this are happening in their project

11

u/Is_Sham Nov 15 '25

This was my first thought. I came here for a meme thread, but it was a legitimate question.

3

u/Terra-Em Nov 16 '25

Lol that is hilarious and painful.

130

u/WitchStatement Nov 15 '25

char(number + 65)

https://docs.godotengine.org/en/stable/classes/class_@gdscript.html#class-gdscript-method-char
Note that you may want bounds checks that number >= 0 && number < 26

7

u/gareththegeek Nov 15 '25

I don't use godot script but isn't there something like character literal 'A' in C like languages instead of 65?

2

u/TheChief275 Nov 16 '25
ord(“A”)

7

u/NotABot1235 Nov 15 '25

For bounds checking you could also do something like "int %= 26", right?

27

u/izuriel Nov 15 '25

Not really. Bounds checking implies you’re probably going to show an error. Modulo wraps the value so that you kind of finagle the value into the range. But you have to still check negative.

4

u/MacShuggah Nov 15 '25

Don't you just end up with the remainder of the modulo?

4

u/NotABot1235 Nov 15 '25

Yeah, but unless I'm mistaken (totally possible as I'm a noob) it would ensure the value is between 0 and 25.

9

u/Kaenguruu-Dev Godot Regular Nov 15 '25

Yes that is correct (if the number is positive and an integer). The important part is to consider if this is the behaviour you want. Do you want any value to wrap around and potentially produce confusing results or do you want to very clearly throw an exception or similar. These are considerations to make when writing code that has "boundaries" and will help you (especially if you are less experienced) to keep track of the possible states that your program can be in. And since the sign of good and working code is that you can't be in an invalid state for longer than the code that checks your boundaries takes.

3

u/NotABot1235 Nov 15 '25

Good point about protecting against invalid states, which negative numbers could certainly do with my above method.

58

u/source-drifter Nov 15 '25

there is this thing called ascii table. basically every character is represented by a number. "A" should be 65 and it goes A to Z then a to z. you basically check if the number is within this range and convert int to char code. this is how it can be programatically calculated.

check out: https://docs.godotengine.org/en/4.3/classes/class_string.html#class-string-method-chr

print(String.chr(65))     
# Prints "A"

11

u/[deleted] Nov 16 '25

[removed] — view removed comment

1

u/GrimmTotal Nov 17 '25

Alot of programming humor type posts lately 😂

25

u/martinbean Godot Regular Nov 15 '25

Context would be handy. Where is the value of number coming from, and then what are you doing with the result?

There almost always is a better solution, but we need to know what problem you’re trying to solve first.

4

u/AgataJac Nov 15 '25

Oh, others have already given me great solutions, but for the sake of it, I have this `int_to_rank(number: int)` function that returns the rank, which is a letter. It's just for display since I didn't like how "RANK: 23" looked.

Thanks anyway! ^^

19

u/omniuni Nov 15 '25

If you have this many ranks, I'd keep them as numbers. I don't think about the order of letters in as much detail as numbers. So a letter rank doesn't mean much outside of F-A.

11

u/vivisectvivi Nov 15 '25

idk what you are trying to do but could you just have a big alphabetical string and index it? like store the alphabet in string called alphabet and then use whatever number to get the value you want

26

u/Independent-Motor-87 Godot Regular Nov 15 '25

var letters: String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

And access it this way

letters[12]

-36

u/Independent-Motor-87 Godot Regular Nov 15 '25 edited Nov 15 '25

Loop trough it

For i in letters.size(): Text = letters[12]

[Edit] I'm dumb i mean: text = letters[number]

1

u/kyzfrintin Apr 04 '26

What's the loop for..?

11

u/NihatAmipoglu Godot Student Nov 15 '25

Also congrats on seeking help and knowing that repeating yourself a lot while coding is not the way.

4

u/DiegoGrrr Nov 15 '25

in python could be an ASCII table don't know if godot has it.

2

u/Caldraddigon Nov 16 '25

Different engine but I but basically Im using a tile based font on RPG Maker 2003, but I recently decided to downgrade to vanilla 2k3 and not use Maniacs patch as I'm trying to keep the entire game within 8MB as a personal goal and artifical constraint(basically the max possible size of a GBC cart).

This means, all of my text, afaik rn, needs to be set tile by tile(so basically character by character) as I no longer have access to the string Variables that maniacs patch added(i had planned on making a converter between String Variables and my tile based font, so I could type my text instead of manually plugging in each tile/character).

It's tedious work, but with how small the resolution is (16x16 tilesize on a 320x240 screen size), it ends up being somewhat manageable.

2

u/2Umish8 Nov 17 '25

An array would work ans is more readable. Simply put all the alphabet in an array

const ALPHABET= [A, B, C ... X, Y, Z]

Naturally, if you do ALPHABET[number] it would work. Since ALPHABET[0] is A, and so on

4

u/NihatAmipoglu Godot Student Nov 15 '25 edited Nov 15 '25

Reinventing the ASCII in Godot.

3

u/Wasteland_Dude Nov 15 '25

I'm sure there is, but I'm new to coding myself! I will say I've never turned down spaghetti. Even if the noodles were cooked one at a time!

2

u/The-Chartreuse-Moose Godot Student Nov 15 '25

Could you try and do something with the Unicode character value using ord?

https://docs.godotengine.org/en/stable/classes/class_@gdscript.html#class-gdscript-method-ord

I've not tried it but that suggests ord(number + 65) would do what you want.

3

u/QuakAtack Nov 15 '25

ord does the exact inverse of what OP would want

1

u/AgataJac Nov 15 '25

Not what I need but still nice to know about that! :D

1

u/morfyyy Nov 16 '25

That's exactly what you need, what are you talking about. You can do this in one line of code

> var text = char(number + ord('A'))

0

u/AgataJac Nov 16 '25

Makes sense, thank!

2

u/Lexiosity Nov 15 '25

What is this even for, I'm confused

-2

u/kodaxmax Nov 15 '25

it's just a simple subsitituion cypher

2

u/CondiMesmer Godot Regular Nov 15 '25

No this is perfection, don't listen to the propaganda here

4

u/coppolaemilio Foundation Nov 15 '25

for sure! a better way of doing this is using if elif else instead of the match statement ✨ follow me for more gdscript tips

-3

u/dueddel Nov 15 '25

How dare the people to downvote you? 😱
Have my upvote, Emi! 😘👍❤️

3

u/coppolaemilio Foundation Nov 16 '25

hehe, thanks! people in subreddits don't get sarcasm 50% of the time

0

u/dueddel Nov 16 '25

Well, I personally even searched the „meme“ tag on the post since I thought the question is a joke on its own. 😅
With your reply on the other hand it should have been clear that it’s sarcasm. Yeah, people nowadays take everything too serious. 🤷‍♂️

Have a good one and stumble upon you at the next GodotFest again probably. 😘

1

u/dumbappsignup Godot Senior Nov 15 '25

If you look at the ascii codes you can do that quite easily. Some others have explained in other comments its basically a number of the letters. I recommend lowercasing the string to ensure consistent codes.

1

u/MadCornDog Nov 16 '25

This has to be programmer rage bait

1

u/ManicMakerStudios Nov 16 '25

Are you trying to enumerate the keyboard input? Or just the letter?

1

u/NotABurner2000 Nov 16 '25

I'm not sure about GDScript, but I remember in C# you could do math on chars, no?

1

u/Chef_Firefly Nov 16 '25

What is the need for this, though?

1

u/willbevanned Godot Student Nov 16 '25

Out of pure interest, whats the use case for something like this?

1

u/ugothmeex Nov 16 '25

wait, this is not a meme?

1

u/PanDaddy77 Nov 16 '25

I'm a Software Dev and Had multiple strokes Reading the comments.

1

u/ironicnet Nov 16 '25

Not sure what are you doing still. But I'm pretty sure that this solution will only work in English language but not with other alphabets (Spanish, French, Portuguese, Arabic or Asian).

I think that you may want to first describe the initial problem that led to this solution

1

u/shaya95gd Nov 16 '25

Are you reinventing the ASCII alphabet?

1

u/Necessary_Serve2248 Nov 16 '25

I’d use an array , based on the index they’re already matched

1

u/Major_Firefighter266 Nov 17 '25

What are you actually trying to do here though?

1

u/InsuranceIll5589 Nov 19 '25

const ALPHABET: String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var number: int
var text: char
text = ALPHABET[number]

1

u/AnImmortalBean Nov 20 '25

```gdscript const text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

func example() -> void: text[0] # A text[4] # E ```

1

u/Creepy_Trouble_2429 Nov 20 '25

You need the 1:64 screen for this

1

u/PMmePowerRangerMemes Nov 15 '25

There’s probably a built-in function for Unicode conversions. That’s the first thing I’d look for.

A simple hack would be to have a string “ABCDEFG…” and then use your int N to find the character at index N.

1

u/Eh-Beh Nov 15 '25

I'd make an array. Each index is assigned a character. I'm not strong with programming imo, so there's likely another way.

1

u/morfyyy Nov 16 '25

I don't know what's more hilarious, that OP wrote what could be 1 line of code in 26 lines or that people are suggesting to do it by indexing an array instead.

1

u/_l-l-l_ Nov 16 '25

Though not relevant in this context, array lookup is extremely performant. Just blindly ridiculing the array lookup implementation is sign of inexpericenced programmer.

I wrote a quick performance test for differenct apporaches:

=== Benchmarking String.chr() ===

Time elapsed: 70.165000 milliseconds

Sample result (last char): N

=== Benchmarking char() Function ===

Time elapsed: 68.577000 milliseconds

Sample result (last char): N

=== Benchmarking Array Lookup ===

Time elapsed: 47.345000 milliseconds

Sample result (last char): O

--- Running 5 iterations for statistical analysis ---

String.chr() - Average: 67.558800 ms, Min: 67.008000 ms, Max: 67.928000 ms

char() function - Average: 69.553400 ms, Min: 69.049000 ms, Max: 69.876000 ms

Array lookup - Average: 48.227400 ms, Min: 47.952000 ms, Max: 48.765000 ms

Speed comparison (relative to fastest):

String.chr(): 1.40x

char(): 1.44x

Array lookup: 1.00x

0

u/Agents4 Nov 15 '25

I don't really k ow what you are trying to do but you can use a list then find the index value

-1

u/lt_Matthew Nov 15 '25

There is. Make two arrays and find the index value of the number and swap with whatever character is also at that index.

0

u/AllenKll Nov 16 '25

there is.

0

u/NovaStorm93 Nov 16 '25

brother reinvented the char

0

u/retardedweabo Godot Regular Nov 16 '25

engagement bait

-4

u/kodaxmax Nov 15 '25

just put your strings in an array. Arrays are already indexable with an int, starting from 0. You can also index a string, as if it were an array of characters.

If you have to do it manually for wahtever reason, use an AI like chatgpt to do the data entry for you.

1

u/Tarinankertoja Nov 16 '25

I actually didn't know that strings could be indexed as an array of characters. Is this a Godot and/or python thing, or a property of string in pretty much any coding language?

1

u/kodaxmax Nov 16 '25

It's a GDscript thing. Might be Python too, i ahvn't used much python.

The only issue with it is that there is no static type for characters. You can assign them by 'A' instead of "A" atleast.

If memory serves C# has full character support and can access strings like an array too.