Re: "Questions that don't deserve their own thread" thread
Posted: Sat Jan 30, 2016 11:49 pm
Oh, that was simple. (i.Thank .. " you.")
Code: Select all
local map = {
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{0, 0, 0, 0, 1, 2, 1, 0, 0, 0, 0 },
{0, 0, 0, 0, 1, 2, 1, 0, 0, 0, 0 },
}
for y,row in ipairs(map) do
for x,tile in ipairs(row) do
-- draw tile to x,y
end
end
Code: Select all
local map = {
[2] = { [5] = 1, [6] = 2, [7] = 1 },
[3] = { [5] = 1, [6] = 2, [7] = 1 },
}
for y,row in pairs(map) do
for x,tile in pairs(row) do
-- draw tile to x,y
end
end
Code: Select all
require 'socket'
local gettime = socket.gettime
function test(use_ipairs)
local map
if use_ipairs then
map = {
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{0, 0, 0, 0, 1, 2, 1, 0, 0, 0, 0 },
{0, 0, 0, 0, 1, 2, 1, 0, 0, 0, 0 },
}
else
map = {
[2] = { [5] = 1, [6] = 2, [7] = 1 },
[3] = { [5] = 1, [6] = 2, [7] = 1 },
}
end
local starttime
local endtime
local sum = 0
starttime = gettime()
if use_ipairs then
for i = 1, 1000000 do
for k, v in ipairs(map) do
for k, v in ipairs(v) do
sum = sum + v
end
end
end
else
for i = 1, 1000000 do
for k, v in pairs(map) do
for k, v in pairs(v) do
sum = sum + v
end
end
end
end
endtime = gettime()
return endtime - starttime, sum
end
-- Ensure both branches are pre-compiled
test(false)
test(true)
print("With pairs:", test(false))
print("With ipairs:", test(true))
Code: Select all
$ love .
With pairs: 0.12001514434814 8000000
With ipairs: 0.094685077667236 8000000
$ luajit main.lua
With pairs: 0.12058019638062 8000000
With ipairs: 0.094517946243286 8000000
$ lua main.lua
With pairs: 1.1777708530426 8000000
With ipairs: 3.2261650562286 8000000
Code: Select all
for y = top, top + height - 1 do
for x = left, left + width - 1 do
-- draw the tile
end
end
Code: Select all
starttime = gettime()
if use_ipairs then
for i = 1, 1000000 do
for y = 1, 3 do
for x = 1, 11 do
sum = sum + map[y][x]
end
end
end
else
for i = 1, 1000000 do
for y = 1, 3 do
if map[y] then
for x = 1, 11 do
if map[y][x] then
sum = sum + map[y][x]
end
end
end
end
end
end
endtime = gettime()
Code: Select all
$ luajit main.lua
With pairs: 0.18178987503052 8000000
With ipairs: 0.046344995498657 8000000
$ lua main.lua
With pairs: 3.0706739425659 8000000
With ipairs: 2.5100657939911 8000000