您的位置:首页 > 其它

Red语言入门(2)—— 第一个Red程序

2015-03-16 09:48 190 查看
几乎所有的编程教程都以一个小例子开始。其目的是让读者准备好开发环境,熟悉编译工具的使用。我们也按照传统,从这最基本的一步开始吧!

不同于大多数编程语言的第一个Hello World程序,我们来做些更有意思事。程序
demo.red 如下:

Red [
    Title:  "Red alpha simple ASCII art demo"
    Author: "Nenad Rakocevic"
    File:   %demo.red
    Tabs:   4
    Rights: "Copyright (C) 2012 Nenad Rakocevic. All rights reserved."
    License: {
        Distributed under the Boost Software License, Version 1.0.
        See https://github.com/dockimbel/Red/blob/master/BSL-License.txt     }
]

data: [
    [0 7 20]
    [2 2 6 7 20]
    [1 2 6 7 20]
    [0 2 6 7 10 14 17 20 20]
    [2 2 6 7 9 10 13 14 16 17 19]
    [1 7 9 10 13 14 16 17 20]
    [0 2 4 5 9 14 16 17 20]
    [2 2 5 6 9 10 16 17 20]
    [1 2 5 6 9 10 13 14 16 17 19]
    [0 2 6 7 10 14 17 20 20]
]

pattern: "Red"
prin newline

foreach line data [
    cursor: 1 + line/1
    line: next line
    gap-start: line/1
    gap-end: line/2
    prin tab
    prin tab
    
    repeat i 21 [
        prin either all [
            gap-start <= i
            i <= gap-end
        ][
            #" "
        ][
            pattern/:cursor
        ]
        if i > gap-end [
            unless tail? line: skip line 2 [
                gap-start: line/1
                gap-end: line/2
            ]
        ]
        
        cursor: cursor + 1
        if cursor = 4 [cursor: 1]
    ]
    prin newline
]
程序有点长,但是没关系,现在我们不需要理解它,我们的目的是学会如何运行这段代码。

首先,下载Red工具链。相对于其他的编程语言动辄上百MB的工具链,Red显得太过苗条,甚至让人怀疑它的能力。你能想象一个不到1MB的工具,包含了两个编译器(Red和Red/System),一个解释器(Red)吗?真可谓是麻雀虽小,五脏俱全。

官方下载地址:http://red.github.io

接着,以Windows平台为例进行操作:

1. 打开CMD,解释执行:

E:\>red-051.exe demo.red

                RedRed              d
                d     d             e
                e     e             R
                R     R   edR    dR d
                d     d  d   R  R  Re
                edRedR   e   d  d   R
                R   e    RedR   e   d
                d    e   d      R   e
                e    R   e   d  d  dR
                R     R   edR    dR d

E:\>
2. 编译后运行。解释执行很方便,缺点是程序运行速度,并且需要有Red解释器才可以运行程序。编译后,会生成一个独立的可执行文件,能够弥补前面说的缺陷。

E:\>red-051.exe -c demo.red

-=== Red Compiler 0.5.1 ===-

Compiling /E/demo.red ...
...compilation time : 241 ms

Compiling to native code...
...compilation time : 13256 ms
...linking time     : 189 ms
...output file size : 348672 bytes
...output file      : E:\demo.exe

E:\>demo.exe

RedRed              d
d     d             e
e     e             R
R     R   edR    dR d
d     d  d   R  R  Re
edRedR   e   d  d   R
R   e    RedR   e   d
d    e   d      R   e
e    R   e   d  d  dR
R     R   edR    dR d
3. 进入REPL环境。

E:\>red-051.exe

-=== Red Console alpha version ===-
Type HELP for starting information.

red>> 1 + 2
== 3
red>> print "你好"
你好
red>> quit

E:\>
好了,现在你已经基本学会了Red工具链的使用,就这么简单!:D

如果了解更多的命令行参数,可以执行:

E:\>red-051.exe -h
童鞋们可以根据帮助说明,尝试编译DLL,交叉编译(在windows上编译Linux或者Mac版本的程序)。在下一篇,我们将正式进入Red语言的学习。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: