2025年11月5日 星期三

Lua for V A P O R C O D E

 7 kyu: V A P O R C O D E

題目是將一串文字,轉成VAPOR code的形式。
我的寫法如下:
local function vaporcode(s)
  local a = ""
  for i = 1, #s do
    local u = s:sub(i, i):upper()
    if u ~= " " then
      a = a .. u .. "  "
    end
  end
    return a:sub(1, -3)
end

return vaporcode
但是別人簡潔的寫法如下:
local function vaporcode(s)
  return s:upper():gsub("%s",""):gsub("%S","%1  "):sub(1,-3)
end

return vaporcode
In Lua's string.gsub function, %1 (or %n where n is a number from 1 to 9) is used in the replacement string to refer to a captured substring from the pattern.
Note: %1是從左到右在pattern中的第1個%值。
例如:
local text = "Hello World"local new_text, count = string.gsub(text, "(%a+)(%s+)(%a+)", "%3%2%1")print(new_text) -- Output: World Helloprint(count) -- Output: 1

%1是抓到Hello
%2是抓到空白" "
%3是抓到World

沒有留言:

張貼留言

Basic Blind Chess的兩大問題

 Basic Blind Chess已經好久沒更新了, Windows版可以獲得最好的遊戲体驗, 但是Android版的,不只是比較舊, 它其實存在兩大問題: 1. 拿子移動時,顯示怪怪的,只顯示前幾個移動的殘影。 這個只有在最早的版本,沒有這個問題, 但是最早的版本實機測試時,...