Rcjp's Weblog

June 2, 2006

LUA Programs

Filed under: misc — rcjp @ 3:40 pm

Been playing with LUA which is a clean simple embeddable language to see how it compares to python. The first thing to write, as all lisp programmers probably do, is a factorial program

    function factorial(n)
       if n == 1 then return 1
       else return n * factorial(n-1)
       end
    end

    print(factorial(10))


I’m a bit suprised there is no default easy way to dump out a table (which is lua’s basic data structure), but found and fiddled with something from the lua
mailing list…

    function mydump(t, indent)
       local indent = indent or 0
       if type(t) == "table" then
          for key, value in pairs (t) do
         io.write(string.rep (" ", indent))
    --   print("key = ", key, "value = ", value)
         if type (value) == "table" then
            io.write(string.format("table[%s]--v\n", key))
            mydump (value, indent + 7)
         elseif type(value) == "function" then
            io.write(string.format("%s\n", tostring (value)))
         else
            io.write(string.format("[%s] => %s\n", tostring (key),value))
         end
          end
       else
          io.write(t .. "\n")
       end
    end


A few test programs…

    function occurences (lst)
       local occur = {}
       for key, value in ipairs(lst) do
          occur[value] = (occur[value] or 0) + 1
       end
       return occur
    end

    z = occurences{'a', 'b', 'a', 'd', 'a', 'c', 'd', 'c', 'a'}
    for key, val in pairs(z) do print(key, val) end


and

    --
    -- read words line at a time
    --
    function readwords1()
       local dict = {}
       local words = assert(io.input("/usr/share/dict/words"))
       for line in io.lines() do
          _, _, word = string.find(line, "^%s*(%w+)%s*$")
          table.insert(dict, word)
       end
       table.sort(dict)
       io.input():close()
       return dict
    end

    --
    -- read whole file then use gfind
    --
    function readwords2()
       local dict = {}
       assert(io.input("/usr/share/dict/words"))
       for word in string.gfind(io.read("*all"), "%w+") do
          table.insert(dict, word)
       end
       table.sort(dict)
       print("size = ", table.getn(dict))
       io.input():close()
       return dict
    end

    --
    -- read whole file using io.open then use gfind
    --
    function readwords3()
       local dict = {}
       local f = assert(io.open("/usr/share/dict/words", "r"))
       for word in string.gfind(f:read("*all"), "%w+") do
          table.insert(dict, word)
       end
       table.sort(dict)
       f:close()
       return dict
    end


    function findwords(word, dict)
       local found = {}
       for _, dictword in next, dict do
          if string.find(dictword, word) then table.insert(found, dictword) end
       end
       return found
    end

    d = readwords3()
    res = findwords("shovel", d)
    for _, w in ipairs(res) do print(w) end


On the lua mailing list I found a nice prog to print out globlals…

    -- find undefined global vars
    -- typical usage: luac -p -l *.lua | lua globals.lua

    local S={}
    local G={}
    local F

    while true do
       local s=io.read()
       if s==nil then break end
       local ok,_,f=string.find(s,"^[mf].-<(.-):[%d,]+>")
       if ok then F=f end
       local ok,_,l,op,g=string.find(s,"%[%-?(%d*)%]%s*([GS])ETGLOBAL.-;%s+(.*)$")
       if ok then
          if op=="S" then S[g]=true else G[g]=F..":"..l end
       end
    end

    for k,v in next,G do
       if not S[k] and not _G[k] then
          io.write(k," may be undefined in ",v,"\n")
       end
    end


and an interesting way of implementing the fibonacci sequence with meta-tables

    fibs = { 1, 1 }                                 -- Initial values for fibs[1] and fibs[2].
    setmetatable(fibs, {                            -- Give fibs some magic behavior.
      __index = function(fibs,n)                    -- Call this function if fibs[n] does not exist.
                   fibs[n] = fibs[n-2] + fibs[n-1]  -- Calculate and memorize fibs[n].
                   return fibs[n]
                end
    })

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: