Lua for loop help!
I have the following code
tile_width = 64;
tile_height = 64;
tile_map = {
{1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,3,1,1,1,1,1,1},
{1,1,1,1,1,3,1,1,1,1,1,1},
{1,1,1,1,1,3,1,1,1,1,1,1},
{1,1,1,1,1,3,1,1,1,1,1,1},
{1,1,1,1,1,1,2,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,2,1,1,1,1,1}
}
i=1;
j=1;
while i<table.getn(tile_map) do
while j<table.getn(tile_map[i]) do
print(tile_map[i][j]);
x = (j * tile_width / 2) + (i * tile_width / 2)
y = (i * tile_height / 2) - (j * tile_height / 2)
print(x);
print(y);
j = j+1;
end
i = i+1;
end
And it works, but it only di开发者_运维百科splays the first row values, and doesn't go onto the second row, third row, etc.
What I am trying to do in another language
for (i = 0; i < tile_map.size; i++):
for (j = 0; j < tile_map[i].size j++):
draw(
tile_map[i][j],
x = (j * tile_width / 2) + (i * tile_width / 2)
y = (i * tile_height / 2) - (j * tile_height / 2)
)
Any idea what I am doing wrong?
Thanks!
Here is a cleaned up version of your code.
Note changes:
- Use
local
variables instead of global. - Use
#
for table size instead oftable.getn()
. - Use numeric
for
loop instead ofwhile
. - Lack of semicolons.
If you'll uncomment io.write()
calls and comment out print
s, you will get your map printed out in a readable way.
local tile_width = 64
local tile_height = 64
local tile_map = {
{1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,3,1,1,1,1,1,1},
{1,1,1,1,1,3,1,1,1,1,1,1},
{1,1,1,1,1,3,1,1,1,1,1,1},
{1,1,1,1,1,3,1,1,1,1,1,1},
{1,1,1,1,1,1,2,1,1,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,2,1,1,1,1,1}
}
for i = 1, #tile_map do
local row = tile_map[i]
for j = 1, #row do
--io.write(row[j])
print(row[j])
local x = (j * tile_width / 2) + (i * tile_width / 2)
local y = (i * tile_height / 2) - (j * tile_height / 2)
print(x)
print(y)
end
--io.write("\n")
end
P.S. Make sure you've read the Programming in Lua 2nd Edition book. Note that the version, available online, is the first edition and it describes older Lua 5.0.
You have to reset j to 1 after each of the inner loops. Because: After the inner loop has been completed for the first time, j will have been incremented 64 times. But you want to start over with j set to 1.
In the code of the other programming language, note that this re-setting of j is taken care of.
精彩评论