Reputation: 6898
I am playing a little bit with Lua.
I came across the following code snippet that have an unexpected behavior:
a = 3;
b = 5;
c = a-- * b++; // some computation
print(a, b, c);
Lua runs the program without any error but does not print 2 6 15
as expected. Why ?
Upvotes: 35
Views: 63933
Reputation: 9821
Lua doesn't increment and decrement with ++
and --
. --
will instead start a comment.
Upvotes: 18
Reputation: 1
You can do the following:
local default = 0
local max = 100
while default < max do
default = default + 1
print(default)
end
Upvotes: -2
Reputation: 255
There are 2 problems in your Lua code:
a = 3;
b = 5;
c = a-- * b++; // some computation
print(a, b, c);
One, Lua does not currently support incrementation. A way to do this is:
c = a - 1 * b + 1
print(a, b, c)
Two, --
in Lua is a comment, so using a--
just translates to a
, and the comment is * b++; // some computation
.
Three, //
does not work in Lua, use --
for comments.
Also it's optional to use ;
at the end of every line.
Upvotes: 0
Reputation: 31
EDIT: Using SharpLua in C# incrementing/decrementing in lua can be done in shorthand like so:
a+=1 --increment by some value
a-=1 --decrement by some value
In addition, multiplication/division can be done like so:
a*=2 --multiply by some value
a/=2 --divide by some value
The same method can be used if adding, subtracting, multiplying or dividing one variable by another, like so:
a+=b
a-=b
a/=b
a*=b
This is much simpler and tidier and I think a lot less complicated, but not everybody will share my view.
Hope this helps!
Upvotes: -2
Reputation:
This will give
3 5 3
because the 3rd line will be evaluated as c = a
.
Why? Because in Lua, comments starts with --
. Therefore, c = a-- * b++; // some computation
is evaluated as two parts:
c = a
* b++; //// some computation
Upvotes: 3
Reputation: 801
There isn't and --
and ++
in lua.
so you have to use a = a + 1
or a = a -1
or something like that
Upvotes: 14
Reputation:
If you want 2 6 15
as the output, try this code:
a = 3
b = 5
c = a * b
a = a - 1
b = b + 1
print(a, b, c)
Upvotes: 4
Reputation: 140234
--
starts a single line comment, like #
or //
in other languages.
So it's equivalent to:
a = 3;
b = 5;
c = a
Upvotes: 40