The reason it desyncs in MP is because you're using local variables to store state data outside of functions.
That means when someone loads a game it populates those variables with data and then when someone else connects it re-populates them and they end up different on the 2 computers.
Simply store the data you use (between functions) in the global table and it fixes that issue.