Insurance was illegal at different times in history because it was considered gambling. Ditto for commodity trading.
Even you look at the structure of a futures contact, the basics look really similar to a bet that can be traded with someone else.
The main differences are the regulatory environment, and the intention the actors in the market have.
Commodities, options, and futures are all legitimately used to hedge against future outcomes. The "gamble" (placing money on a future outcome) is a mechanism for the main goal: protection against instability.
When you look at stocks and - in particular - derivatives, it starts to look a lot closer to how gambling is structured. I'm pro stock market, but that doesn't mean I won't admit that the line between it and gambling is pretty hard to draw. It's a lot more grey than people give credit for