m-renaud
m-renaud

Reputation: 1265

Idiomatic Way Of Creating Class Instances From Config Files

EDIT: I have restructured the question so it is (hopefully) easier to answer. I'm new to CL so it's sometimes hard to describe what I'm trying to do when I'm not even sure what the best way to describe it would be :P

I've been learning some Common Lisp over the past couple weeks and am wondering the best way to create an instance of an object given a configuration file that defines some of the slot values for the class but the values need to be normalized in some form before they are assigned.

So, for a simple example, if I have the following class:

(defclass my-class ()
  ((name
    :initarg :name
    :accessor name)
   (x
    :initarg :x
    :initform 10
    :accessor x)
  (y
   :initarg :y
   :initform nil
   :accessor y)))

and

(defmethod initialize-instance :after ((obj my-class) &key)
  (with-slots (x y)
      obj
    (setf y (* 2 x))))

I would like a way of specifying in an external file, say instance-a.lisp

(possibly-some-macro "A"
    :x 5)

But when constructing an instance the value x must be normalized first some how. The eventual call to make-instance would look something like this:

(make-instance 'my-class 
               :name (name-value-from-config) 
               :x (normalize (x-value-from-config))

Where (name-value-from-config) would be "A" and (x-value-from-config) would be 5. NOTE: These two forms are only here for placeholders to indicate that it should be constructed with the values from the configuration.

My initial thought would be to turn whatever is in the config file into a hash table or a plist with the appropriate keys.

Upvotes: 1

Views: 210

Answers (1)

Rainer Joswig
Rainer Joswig

Reputation: 139311

It's not clear to me what you really want to do.

Why would one use a macro to create an object?

  • the macro creates compile-time side-effects. For example the object should be available during file compilation.

  • the macro provides a more convenient syntax

But for all other purposes don't try to do something clever. Usually I would just LOAD a Lisp file for configuration.

(defparameter *instance-a*
   (make-instance 'my-class :x 5 :y '(1 2 3)))

If the class needs to be configured:

(defparameter *a-class* 'my-class)

(defparameter *instance-a*
   (make-instance *a-class* :x 5 :y '(1 2 3)))

Upvotes: 2

Related Questions