r/lua • u/Murky_Construction82 • Jul 25 '26
Can anybody help me learn if statements in Lua?
I'm new to Lua, trying it out after a few years doing amateur projects in Python. At first I thought this weird error was just a bug or something in my IDE's Lua extension, but an online compiler had the same issue!
I played around a bit and eventually ended up on this absolutely mind-boggling example. These two if then statements look like they're constructed exactly the same--I literally copy-pasted the first one and changed the conditional and message. Yet only the first one runs! The second gives me an error: 'then' expected near '='. This was consistent across the two compilers I used.
```Lua
roll = math.random(6)
print(roll)
if roll > 4 then
print("Success!")
end
if roll = 1 then
print("Critical failure!")
end
```
19
u/Chen-Zhanming Jul 25 '26
==is equal :)8
u/GlassCommission4916 Jul 25 '26
In lua
=is the assignment operator,==is for equality.3
u/Sckip974 Jul 26 '26
Don't forget to mix the RNG seeds to avoid always getting the same dice roll.
-- lua
math.randomseed(os.time())
local randomNumber = math.random(1, 6)
print(randomNumber)
I would like to suggest two Lua books online, as you say you are new to the language, of course you probably already know 3/4 of it but personally these helped me (and going back to the basics is sometimes good)
https://rvagamejams.com/learn2love/
https://sheepolution.com/learn/book/contents
5
u/Foamie62 Jul 25 '26
roll = 1.
is an assignment, not a comparison expression. To check equality you need to use a double equals
roll == 1
4
u/SayuriShoji Jul 25 '26 edited Jul 25 '26
To compare things for equality, you use
==(are they equal) or~=(are they not equal):if roll == 1 thenprint("Critical Failure")endWriting
roll = 1is an assignment (roll gets a new value of 1), which does not return a valid comparison value for theif ... thento use1
u/ScholarNo5983 Jul 26 '26
When I use the Lua bytecode compiler to lint your code using this command:
It reports this issue with the code:
NOTE: This is line 9 in in the
test.luafile: