lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


A nifty little script was posted to the Python Tutor list a few days
ago and for practice I decided to rewrite it using Lua-5.0-alpha.
The conversion was simple except that I couldn't think of an elegant
way to emulate the tuple-indexed dictionary.  The initialization of
STARTING_ROW doesn't feel quite right either though it does work (and
that, I suppose, is the most important part).

How would you have written this in Lua?  My working attempt is included
at the bottom.

=== begin ascii-art.py ===

"""A small ascii-art program in Python.
Danny Yoo (dyoo@hkn.eecs.berkeley.edu)

See:

    http://www.wolframscience.com/preview/nks_pages/?NKS0032.gif

and Wolfram's "A New Kind of Science" for more information about this
fascinating topic.
"""

import sys

"""Wolfram's automaton uses eight rules for generating the next row of
output.  Let's take a look at them."""
RULE_100 = { (1, 1, 1) : 0,
             (1, 1, 0) : 1,
             (1, 0, 1) : 1,
             (1, 0, 0) : 0,
             (0, 1, 1) : 1,
             (0, 1, 0) : 1,
             (0, 0, 1) : 1,
             (0, 0, 0) : 0 }

def drawRow(row):
    for character in row:
        if character: sys.stdout.write('O')
        else: sys.stdout.write('.')
    sys.stdout.write('\n')

STARTING_ROW = [0]*2 + [0]*70 + [1] + [0]*2

def applyRuleOnRow(rule, row):
    new_row = [0]
    for i in range(1, len(row)-1):
        triple = (row[i-1], row[i], row[i+1])
        new_row.append(rule[triple])
    new_row.append(0)
    return new_row

if __name__ == '__main__':
    row = STARTING_ROW
    for i in range(70):
        drawRow(row)
        row = applyRuleOnRow(RULE_100, row)

=== end ascii-art.py ===

=== begin ascii-art.lua ===

RULE_100 = { ["111"] = 0,
             ["110"] = 1,
             ["101"] = 1,
             ["100"] = 0,
             ["011"] = 1,
             ["010"] = 1,
             ["001"] = 1,
             ["000"] = 0 }

function drawRow(row)
    for _,character in ipairs(row) do
        if character == 1 then io.write('O')
        else io.write('.')
        end
    end
    io.write('\n')
end

STARTING_ROW = {}
for i=1,75 do
    if i ~= 73 then table.insert(STARTING_ROW,0)
    else table.insert(STARTING_ROW,1)
    end
end

function applyRuleOnRow(rule, row)
    local new_row = {0}
    for i = 2, table.getn(row)-1 do
        local triple = string.format("%s%s%s", row[i-1], row[i], row[i+1])
        table.insert(new_row, rule[triple])
    end
    table.insert(new_row,0)
    return new_row
end

if arg then
    local row = STARTING_ROW
    for i = 1, 70 do
        drawRow(row)
        row = applyRuleOnRow(RULE_100, row)
    end
end

=== end ascii-art.lua ===

Thanks,
Dean.

--
E-Mail:  sessile@in-gen.net