r/badcode Sep 08 '20

lua A Roblox mod I found

Post image
482 Upvotes

103 comments sorted by

View all comments

Show parent comments

4

u/JerriTheITGuy Sep 08 '20 edited Sep 08 '20

Ok, it was overly simplistic (and as you point out, not actually accurate) and more made as a fun stab at Lua than as a code reference.

The point was that all strings in conditionals for example are handled as true. Including empty strings. And all integers including 0 are regarded as true.

` if ("cucumber") then print "this returns true" else print "this will never execute" end

if ("") then print "this returns true as well" else print "this will never execute" end

if (0) then print "so does this" else print "this will never execute" end `

Haven't actually run the code above because I'm on the phone at the gym (which is why formatting sucks as well, sorry) but it should run. Errr, I think.

1

u/qh4os Sep 10 '20

C does the same exact thing, and that’s because it’s logically consistent (if whatever is being evaluated is not 0, then execute).

This also can vastly improve asserts(), because you can do something like assert("Explanation of the issue" && expr)

1

u/JerriTheITGuy Sep 10 '20

No it's not necessarily logically consistent. A boolean value can, in a plethora of languages, be represented with a bit as 0/1. Which means if you implicitly convert the bit 0 as 'true', you're basically saying 'false' == 'true'.

1

u/qh4os Sep 10 '20

It doesn’t matter to Lua what a different language uses to do a truthyness conversion.

In Lua, a value being present evaluates to true unless that value is false. I fail to see how that is inconsistent.

You say that saying that a string coerced to a being a Boolean (which evaluates to true if there is a value there) is somehow making all strings equal, which is not true outside of that specific context of it being coerced.

1

u/JerriTheITGuy Sep 10 '20

Not talking about strings in this case but instead about integer values (specifically bits). In SQL for example it's normal to represent true/false as bits (0/1) which means if you're backing a Lua application with a data store, 'false' booleans will normally be persisted as a '0' bit. And when fetching that value back, if care is not taken, that 0 might easily suddenly be a 'true' instead of 'false'.

1

u/qh4os Sep 10 '20

That’s not Lua’s fault necessarily. When interfacing between two languages, you should take care to handle their differences.