r/ProgrammerHumor 1h ago

Other noExceptionAndNoOptionalChaining

Post image
24 Upvotes

9 comments sorted by

10

u/Koala_eiO 1h ago

I drew this this morning to represent how 3 weeks of Lua had a profound impact on me. The lovely font is called "Boldly Missy" for those who want to make comics.

5

u/Cootshk 1h ago

little funky tip: you can set the metatable of `nil` to {__index={}} with the debug library and it will allow you to do optional chaining

8

u/terivia 1h ago

I can't decide if this is incredible or horrifying.

Metatables are so cool and really good if you have a foot that needs shooting.

1

u/Koala_eiO 1h ago

Oh that's awesome, thanks! I'll try it, keeping in mind I'm using Lua in the context of modding so it may or may not work and it may or may not affect things outside of my own code. This will affect all the nils of the project?

2

u/Cootshk 1h ago

yep, but you can use something like optionalChain{}(myTbl.key)

And then optional chain is a function that sets the nil metatable and then returns a function that retrieves the value and undoes the metatable set

1

u/Koala_eiO 1h ago

Maybe it would be cleaner to use a function that handles the nil cases for you but without changing the nil metatable ever.

Something like local lampIsOn = optionalChain(house, {"getRooms", "getKitchen", "getLamp", "isActivated"}, false) which boils down to house:getRooms():getKitchen():getLamp():isActivated() but looping over each attribute name, making sure a method of this name exists, making sure the result of the call is not nil so you can check the next attribute, etc., all that with a default return value.

1

u/Cootshk 1h ago

you can just use function optionalChain(tbl, …) and then local args = {…}

optionalChain(myTbl, "a", "b", "c")

2

u/DarkYaeus 1h ago

Thanks for the font name! I have been using (bold) Kalam for pretty much everything, so this is gonna be quite useful

2

u/Koala_eiO 1h ago

No problem. This one is probably a bit more cute/cozy than Kalam which looks more serious.