Discord
Login
Community
DARK THEME

Why can't I compare two lists?

For example:

list1 = [1,2,3,4]
list2 = [1,2,3,4]
if list1 == list2 then
  print("worked")
end

This returns nothing. Is this a bug?

No, you need to create a loop, not use if. First, you need elements that distinguish the two lists and that, if necessary, belong to the list. Use a for loop (which checks every second) if e or s belongs to the list. I'll give you an example

init = function()
  
list1 = [1,2,3,4]
list2 = [1,2,3,4]
end

update = function()
  for e in list1 //We check if object e belongs to the list with this loop
  end
  for s in list2 //same for s
  end
  if e == s then //and now if it belongs we write worked
    print("worked")
    end
end

draw = function()
end

Rylotox, thanks for trying to help but I tested it out and all that does is check if the last element in the list is equal (idk ig thats just the way the engine assigns variables). If you were to change any other element in the list but kept the last element the same it would still work.

hey, sorry my last code was a bit fast and didnt work great. The problem is that in microscript (and many other languages), list1 == list2 only checks if they are the exact same object in memory, not if the numbers inside are the same. To fix this, u need to check every position one by one. If one number is different, then the lists are not the same. Try this function, it should work for you:

compare = function(l1, l2)
  if l1.length != l2.length then return false end
  
  for i = 0 to l1.length - 1
    if l1[i] != l2[i] then return false end
  end
  
  return true
end


if compare(list1, list2) then
  print("yeah")
end

Rylotox, Yes! This works great! Thanks a lot for your help. And thanks for your explanation, I didn't know that that's how the engine checks lists/objects

yw happy to help you ^o^

I think you could overload the compare operator == to perform a list compare. It's in the advanced programming docs, overloading core types.

Here is an example. Extending List with a compare works, but the overload doesn't work, yet.

https://microstudio.io/i/mrderry/test2/

P.s. as List already has a compare, as used in the question example, maybe the equal operator can't be overloaded.

Post a reply

Progress

Status

Preview
Cancel
Post
Validate your e-mail address to participate in the community