Lua: Writing Files

From Mario Fan Games Galaxy Wiki
Revision as of 22:38, 5 January 2009 by Xgoff (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Lua
Lua.gif
Basics
Intermediate
Advanced
XLua
Add to this template
 Standardwikimessagebox.png This article assumes the use of Lua 5.1.

Information may not be accurate or may need revision if you are using a different version.

 Stub.png This article or section is in need of expansion.

Please add further information.

Writing to a file in Lua is a simple process. For this tutorial, we will write a script that generates a few polygons and exports them as an SVG file.

-- a function to generate regular polygons
function polygon(x, y, sides, radius)
    local points = ""
    local ang_offset = 360 / sides
    for p = 1, sides do
        local point_angle = math.rad(p * ang_offset)
        local point_x = math.cos(point_angle) * radius + x
        local point_y = math.sin(point_angle) * radius + y
        points = points .. point_x .. "," .. point_y .. " "
    end
    return '<polygon points="' .. points .. '" /> \n'
end

-- use a variable to hold the file handle, and open a new file
svg = io.open("./polygon_lua.svg", "wb")
io.output(svg)

-- write the start of the svg info 
svg:write('<?xml version="1.0" standalone="no"?>', '\n')
svg:write('<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">', '\n')
svg:write('<svg width="640" height="480" xmlns="http://www.w3.org/2000/svg" version="1.1">', '\n')

-- draw a few polygons
svg:write(polygon(200, 120, 12, 30))
svg:write(polygon(300, 300, 22, 64))
svg:write(polygon(128, 256, 5, 50))

-- write the end of the svg info
svg:write('</svg>', '\n')

-- we're done with the file, so close it
svg:flush()
svg:close()