P
P
p3trukh1n2019-06-10 14:35:41
Lua
p3trukh1n, 2019-06-10 14:35:41

How to use if with multiple values?

Good afternoon.
I started learning LUA, and then a question arose:

function streetIsMyHome()
  return 1, 2, 3
end

if streetIsMyHome() == 1, 2, 3 then
  print("Working")
end

But of course it throws an error.
So, how can you compare multiple values?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dollar, 2019-06-10
@p3trukh1n

local x, y, z = streetIsMyHome()
if x == 1 and y == 2 and z == 3 then
  print("Working")
end

If you do not want to "garbage" variables in the space of the current file or the current scope, then:
The code
function streetIsMyHome()
  return 1, 2, 3
end

do
  local x, y, z = streetIsMyHome()
  if x == 1 and y == 2 and z == 3 then
    print("Working")
  end
end

Another option is to write your own comparison function:
The code
function isEqualAll(...) --сравнивает первую половину аргументов со второй
  local t = {...}
  local half = math.floor(#t/2 + 0.5);
  for i=1,half do
    if t[i] ~= t[i+half] then
      return false
    end
  end
  return true
end

function streetIsMyHome()
  return 1, 2, 3
end

if isEqualAll(1,2,3,streetIsMyHome()) then
  print("Working")
end

But the most correct and beautiful thing is to make a separate function for each specific task:
The code
function streetIsMyHome()
  return 1, 2, 3
end

function checkStreetIsMyHome(a,b,c)
  local x,y,z = streetIsMyHome()
  return a==x and b==y and c==z
end

if checkStreetIsMyHome(1,2,3) then
  print("Working")
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question