Archive for 2010年6月23日|Daily archive page

init.lsp と include について

(この blog は、“short short story または 晴耕雨読な日々”に掲載したものの再掲です。スクリプトも含め、一部加筆修正してあります。)

newLISP の起動時、起動ディレクトリに init.lsp があると、それを読み込みます。
つまり、 init.lsp を用意することで、お好みの newLISP に変身させられます(笑)。
私が使っている init.lsp は、次のようになっています。

(context 'MAIN:include)
; http://www.newlisp.org/index.cgi?page=Code_Snippets
(define error "")
(define modules '())
(define (include:include mfile)
    (unless (find mfile modules)
      (when (catch (if (file? mfile) (load mfile) (module mfile)) 'error)
        (push mfile modules -1))))

(context 'MAIN:type-of)
; http://static.artfulcode.net/newlisp/util.lsp.src.html
(define types '("boolean" "boolean" "integer" "float" "string" "symbol" "context"
                "primitive" "primitive" "primitive" "quote" "list" "lambda" "macro"
                "array"))
(define (type-of:type-of x)
  (let (type (types (& 0xf ((dump x) 1))))
    (if (and (= "list" type) (context? (first x)))
          (name (first x))
          type)))
(context MAIN)
(include "macro.lsp")
(include "newlisp-utility.lsp")

このように、この blog で紹介するスクリプトの先頭で使っている、あるいは、使うことになる関数include は、私の場合、init.lsp で定義しています。
関数include は、Common Lisp の require に相当します
ここで定義している関数include は、引数として与えられたファイル名のファイルがあれば、それを load し、なければ、環境変数NEWLISPDIR下の modulesディレクトリから load します。
どちらにもなければ、nil を返します。つまり、戻り値を見ることで、正常に読み込まれたかどうかを判定できます。エラー内容は、文字列変数include:error に入ります。
ロードしたファイル名は、リスト変数include:modules に入っています。
また、関数tyoe-of は、文字通り、引数の型を返します。newLISP組込みで入っていても良さそうですが、ArtfulCode の Module: util に定義してあるのを使わせてもらっています。デバック時に重宝します。
あとは、おなじみ、macro.lsp日本語訳) と拙作newlisp-utility.lsp を include しています。
これだけ init.lsp で用意しておけば、以降の blog で紹介するスクリプトがすんなり動きます。(笑)
便利な init.lsp ですが、何らかの事情で、読み込みたくない時は、

newlisp -n

で、起動すれば、素の newLISP が立ち上がります。

以上、如何でしょうか?