有没有办法在Common-Lisp中不传递参数,而不是传递"NIL"? [英] Is there a way to not pass an argument in Common-Lisp instead of passing "NIL"?

查看:107
本文介绍了有没有办法在Common-Lisp中不传递参数,而不是传递"NIL"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在根据用户输入来调用函数,但是有些具有两个参数,而另一些则只有一个.代替在每个函数上都使用& optional参数(并且从不使用),有没有一种方法可以简单地在其值为"NIL"时不传递参数?

I'm calling functions according to user input, but some have two parameters and others just one. Instead of using &optional parameter on every function (and never using it), is there a way to simply not pass an argument when it's value is "NIL"?

这是一款用于交互式小说游戏的游戏,在该游戏中,用户键入一些命令,然后将这些命令转换为函数调用.

This is for an interactive fiction game, in which the user type some commands and these are converted into function calls.

(defun inputs (state)
    (format *query-io* "> ")
    (force-output *query-io*)
    (let* ((entry (cl-ppcre:split "\\s+" (string-downcase (read-line *query-io*))))
      (function (car entry))
      (args (cdr entry)))
      (if (valid-call function)
      (funcall (symbol-function (read-from-string function))
           state
           args)
      (progn
        (format *query-io* "Sorry, I don't know the command '~a'~%~%" function)
        (inputs state)))))

如果用户输入是装备剑",我需要调用传递(剑")作为参数的函数装备",但是如果用户输入是状态",则需要调用函数状态"而不传递"args",而不是将其传递为"NIL"

If the user input is "equip sword", I need to call the function "equip" passing the '("Sword") as argument, but if the user input is "status", I need to call the function "status" without passing the 'args', instead of passing them as "NIL"

推荐答案

我认为您想使用 apply 代替 funcall find-symbol 代替 read-from-string (这对于 destructuring-bind 代替 let* :

I think you want to use apply instead of funcall, find-symbol instead of read-from-string (this is actually important for security reasons!) and destructuring-bind instead of let*:

(defun inputs (state)
  (format *query-io* "> ")
  (force-output *query-io*)
  (destructuring-bind (command &rest args)
      (cl-ppcre:split "\\s+" (string-downcase (read-line *query-io*)))
    (if (valid-call command)
        (apply (find-symbol command) state args)
        (progn
          (format *query-io* "Sorry, I don't know the command '~a'~%~%" command)
          (inputs state)))))

使用apply可使您的命令接受任意数量的参数,而不是一个.

Using apply lets your commands accept an arbitrary number of arguments instead of one.

实际上,您的valid-call应该应该返回要调用的函数:

In fact, your valid-call should probably return the function to be called:

(let ((f (valid-call function)))
  (if f
      (apply f state args)
      ...)

这篇关于有没有办法在Common-Lisp中不传递参数,而不是传递"NIL"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆