Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Ternary operator question, why must I use a function rather than inputting the result as is?

I was messing around, I don't normally use Ternary operators so I decided to see what all I could do with it.

Ended up making this:

x={}
x.a = true
doOne = function()
    x.a = 'hi'
    return 'hi'
end
doTwo = function()
    x.a = 'bye'
    return 'bye'
end
print(10==true and doOne() or doTwo())
print(x.a)

However in the process of making whatever that is, I realized that I can't do this:

print(10==true and x.a = "hi" or x.a = "bye")
print(x.a)

Why is that?

Since it acts somewhat like an if statement, if I do that surely nothing should go wrong, putting it in a function seems too long and there is probably a shorter way.

I tried putting a return behind it and tried using rawequal, tried using load() even though I couldn't find much documentation on it.

Is using a function the only valid solution or is there a shorter way? This could be very helpful for code golf :wedoalittletrolling:

1 answer

✓ Accepted answer

load is newer version of loadstring (Which will be deprecated). The only difference is it does not accept binary strings and it also is not in Luau. So with that you can golf it like this:

x={}
x.a = true

print(10==true and load("x.a='hi'return(x.a)")() or load("x.a='bye'return(x.a)")())
print(x.a)
-- "bye
-- "bye"

Lua syntax does not allow value assignment in a function call. You can also shorter your code by merging the two functions into one:

x={}
x.a = true
doBoth = function(v)
	x.a = v
	return x.a
end
print(10==true and doBoth("hi") or doBoth("bye"))
print(x.a)
-- "bye
-- "bye"

rawset will also work but it will return table and not bye string:

x = {}
x.a = true

print(10==true and rawset(x, "a", "hi") or rawset(x, "a", "bye"))
print(x.a)
-- {...}
-- "bye"

So as you see the first method is the most efficient, with max level golfing i could get it look like this:

x={a=true}
s,r="x.a=","return(x.a)"

print(10==true and load(s.."'hi'"..r)() or load(s.."'bye'"..r)())
print(x.a)

1 comment

0

Excellent answer, I tried using rawset and load yesterday but it was slightly confusing since I never used them before, Thank you for making this post :o

This discussion is preserved as it was. New answers, comments, and votes are closed.