dcearth/cities.lua

61 lines
1.5 KiB
Lua
Raw Normal View History

2023-04-28 17:35:52 +00:00
--Load and save the fixed width plaintext data used by DEFCON.
local t = {}
local io = io
local table = table
local tonumber = tonumber
local lfs = love.filesystem
local lg = love.graphics
local cities
local points = {}
local caps = {}
function t.draw()
lg.points( points )
end
function t.drawCapitals()
lg.points( caps )
end
function t.load( filename )
cities = {}
local n = 0
local idxPts = 1
local idxCaps = 1
for line in assert( io.lines( filename ), "Error: could not open cities.dat" ) do
n = n + 1
local _, _, x, y, pop, capital = line:sub( 83 ):find( "(%g+)%s+(%g+)%s+(%g+)%s+(%g+)" )
x, y, pop, capital = tonumber( x ), tonumber( y ), tonumber( pop ), ( tonumber( capital ) > 0)
local city = {
name = line:sub( 1, 39 ):gsub("%s+$",""),
country = line:sub( 42, 82 ):gsub("%s+$",""),
x = x, y = y, pop = pop, capital = capital
}
cities[n] = city
points[idxPts], points[idxPts + 1] = x, y
idxPts = idxPts + 2
if capital then
caps[idxCaps], caps[idxCaps + 1] = x, y
idxCaps = idxCaps + 2
end
end
print( "LOADED", filename, n )
return setmetatable( cities, {__index = t } )
end
function t.save( cities, filename )
local str = {}
for n, city in ipairs( cities ) do
str[n] = ("%-40s%-40s%f %f %d %d"):format( city.name, city.country, city.x, city.y, city.pop, city.capital and 1 or 0 )
end
assert( lfs.write( filename, table.concat( str, "\n" ) ) )
print( "Saved", filename )
end
return t