What is the use of variables with multiple operators?

A couple examples are below:

local isTable = type(value) == "table"
propertyGoals[property] = isTable and value[i] or value (value is a parameter from a function written earlier)

Is the top one to set a value equal to multiple different things, or is it something else? As for the second line, how does that even work? It feels arbitrary, and I’m confused overall.

Kinda, it will set the value to either true or false depending on the results of the equality operator.

It’s a short cut for

local IsTable
if type(value) == "table" then
    IsTable = true
else
    IsTable = false
end

For the second one it’s also a shortcut because lua does read the and evaluate the code left to right and does what is known as short-cut evaluation or short circuit evaluation

isTable and value[i] or value

First it checks isTable, if it is true it will go on to index the table value[i] and assign the variable to that.

If isTable is false then it will the and and go straight to returning the “value”.

You can also use if statements instead here is how the same logic looks like

If isTable then
    propertyGoals[property] = value[i]
else
   propertyGoals[property] = value
end

For more examples see the lua manual for what values does the logical operations return

https://www.lua.org/pil/3.3.html

3 Likes