Game Development Reference
In-Depth Information
table portion, you have to use the pairs() function. This will loop through the
entire table.
test ={x=5,y=10,z=15,20,25}
-- This block will print out:
-- 1 20
-- 2 25
for index, value in ipairs(test) do
print(index, value)
end
-- This block will print out:
-- 1 20
-- 2 25
-- y 10
-- x 5
-- z 15
for key, value in pairs(test) do
print(key, value)
end
Did you notice the odd ordering in the second version of the loop? The reason is
because the non-array part of the table is a hash map, so the ordering is not defined.
You get similar behavior looping through an STL map. Use ipairs() to loop over
the array part of the table and use pairs() to loop over everything in the table.
Operators
Lua supports a number of operators like you
d expect in any language. For basic math-
ematics, it supports addition (+), subtraction (
'
), multiplication ( * ), division (/), mod-
ulo (%), exponentiation (^), and unary negation (-). These all work like the ones in C+
+, except for the exponentiation operator, which C++ doesn
'
t have. This operator takes
the value on the left and raises to the power of the value on the right. For example:
x=2^4 --x=16,or2-to-the-4 th power.
You may notice a few missing operators here. Lua doesn
t support increment (++) or
decrement (--) operators, nor does it support the combo assignment operators that
also perform a mathematical operation (+=, -=, *=, etc.).
Lua ' s relational operators are also rather similar to C++. It has equality (==), inequal-
ity (
'
=), less-than (<), greater-than (>), less-than or equal-to (<=), and greater-than
or equal-to (>=). Note that the inequality operator is not the typical one you may be
used to. They all work like you would expect from other languages.
˜
 
 
Search WWH ::




Custom Search