跳轉到內容

Rebol 程式設計/reword

來自華夏公益教科書
REWORD source values /escape char /into output
>> reword "$1 is $2." [1 "This" 2 "that"]
== "This is that."

將值替換到模板字串中,返回一個新的字串。

REWORD 是一個函式值。

  • source -- 模板序列(或帶有轉義序列的字串)(型別:any-string)
  • values -- 值和替換的配對(如果為函式,將被呼叫)(型別:map 物件塊)
  • /escape -- 選擇您自己的跳脫字元(塊模板沒有轉義)
    • char -- 使用此跳脫字元(預設 $)(型別:char any-string)
  • /into -- 插入到緩衝區中(返回插入後的位置)
    • output -- 緩衝區序列(修改後的)(型別:any-string)

原始碼

[編輯 | 編輯原始碼]
reword: make function! [[
    {Substitutes values into a template string, returning a new string.}
    source [any-string!] "Template series (or string with escape sequences)"
    values [map! object! block!] {Pairs of values and replacements (will be called if functions)}
    /escape {Choose your own escape char (no escape for block templates)}
    char [char! any-string!] "Use this escape char (default $)"
    /into {Insert into a buffer instead (returns position after insert)}
    output [any-string!] "The buffer series (modified)"
    /local vals word a b c d
] [
    output: any [output make source length? source]
    vals: make map! length? values
    foreach [w v] values [
        unless string? :w [w: to string! :w]
        unless empty? w [poke vals w unless unset? :v [:v]]
    ]
    word: make block! 2 * length? vals
    foreach w vals [word: reduce/into [w '|] word]
    word: head remove back word
    escape: [c: word d: (
            output: insert insert/part output a b vals/(copy/part c d) :b
        ) a:]
    char: to string! any [char "$"]
    either empty? char [
        parse/all source [
            a: any [b: [escape | skip]]
            to end (output: insert output a)
        ]
    ] [
        parse/all source [
            a: any [to char b: char [escape | none]]
            to end (output: insert output a)
        ]
    ]
    either into [output] [head output]
]]
華夏公益教科書