Does roblox have somthing like this:
Instead of using a function to return the parent of the frame with this line.
frame.Parent = location == "Test" or "Test1"? testFrame : test1Frame
Does roblox have somthing like this:
frame.Parent = location == "Test" or "Test1"? testFrame : test1Frame
The only place where you can use the ?
operator is on types or function return types. Correct me if i’m wrong, But it determinates if something can be any
(anything that is not nil) or nil
. Basically, it’s like a question, “Is it x?”
type StringOrNil = string? -- Could also be string | nil
function ReturnSomething(): any?
-- Return a value, Will either be a nil value or non-nil value
end
I see, because my current way of getting the parent is this:
local function parent()
if location == "Test" then
return testFrame
else
return test1Frame
end
end
frame.Parent = parent()
I’d like to know if there is an alternative way.
You can try using the built-in Luau feature which allows you to use if
statements inside return functions and variables. Which is the equivalent of doing if x then else y end
, It would look like this:
local function SetParent(Location: string)
return if Location == "Test" then testFrame else test1Frame
end
The technical term here is a ternary operator, and Lua does have an implementation. Unlike programming languages, in Lua you can define as many expressions as you need:
local input = 50
local someResult = (input > 45 and input < 100 and input) or nil
--//^ should be assigned the original value, which was 50, as both operand expressions of 'and' evaluate to true, so input is then used.
Ternary operator?
Here is how you do it
local Value = 50 > 0 and 2 or 1
--Value will be equal to 2 since 50 is more than 0
The user above me did it first