[转载]SDL 用法,第 4 部分:lex 和 yacc - 构建用于脚本和 GUI 设计的语法分析器

本文介绍了在开发游戏Pirates Ho!时如何使用SDL、lex和yacc创建一个灵活的脚本语言。通过Makefile构建语法分析器,并实现eval_getinput()函数从文件或内存中获取输入,yyparse()进行分析。屏幕描述和小部件属性由分析器处理,回调函数由脚本解析。文章作者是SDL库的作者Sam Lantinga和Loki Entertainment Software的技术作家Lauren MacDonell。
摘要由CSDN通过智能技术生成
SDL 用法,第 4 部分:lex 和 yacc
构建用于脚本和 GUI 设计的语法分析器

Sam Lantinga 和 Lauren McDonell
Loki Entertainment Software
SkilledNursing.com
2000 年 5 月

内容:
另一段 bison
从基础开始
提供输入
将 lex 和 yacc 与 C++ 一起使用
从字符串分析
使用多个语法分析器
脚本语言
GUI 示例
结束语
参考资料
关于作者

在这部分中,我们将讨论所有 Linux 程序员工具库中的两种实用工具:lex 和 yacc。这些工具让我们轻松地构建了在我们基于 SDL 的 Linux 游戏 Pirates Ho! 中使用的脚本语言和 GUI 框架。

在设计 Pirates Ho! 时,我们需要一种简便的方法向玩家描述界面和对话框选项。我们需要简单、一致且灵活的语言来进行描述,因此我们寻找可以帮助我们构建脚本语言的工具。

谁想要另一段 bison?
我还在学校时,就已经对 "yacc" 这个词充满恐惧。它让我想到那些头发凌乱、面色苍白的学生低声念叨着编译器和符号表。所以我非常小心,尽量避免使用编译器类。但在开发游戏时,我鼓起勇气使用 yacc,希望它可以使编写脚本变得容易些。最后,yacc 不仅使编写脚本变得更容易,还使这个过程很有趣。

从基础开始
yacc 实际上非常易于使用。只要提供给它一组描述语法的规则,它就可以分析标记,并根据所见到的采取操作。对于我们使用的脚本语言,我们希望由浅入深,最初只是指定一些数字及其逻辑运算:

eval.y

%{
/* This first section contains C code which will be included in the output
   file.
*/
#include <stdlib.h>
#include <stdio.h>
/* Since we are using C++, we need to specify the prototypes for some 
   internal yacc functions so that they can be found at link time.
*/
extern int yylex(void);
extern void yyerror(char *msg);
%}

/* This is a union of the different types of values that a token can
   take on.  In our case we'll just handle "numbers", which are of
   C int type.
*/
%union {
	int number;
}

/* These are untyped tokens which are recognized as part of the grammar */
%token AND OR EQUALS

/* Here we are, any NUMBER token is stored in the number member of the
   union above.
*/
%token  NUMBER

/* These rules all return a numeric value */
%type  expression
%type  logical_expression and or equals
%%

/* Our language consists either of a single statement or of a list of statements.
   Notice the recursivity of the rule, this allows us to have any
   number of statements in a statement list.
*/
statement_list: statement | statement_list statement
	;

/* A statement is simply an expression.  When the parser sees an expression
   we print out its value for debugging
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值