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

2025年11月2日 星期日

Lua基本運算的簡潔寫法

 7 kyu: Dot Calculator

這題是用"."點的數目表示數字,並給operator做運算。
我的寫法是:
return function(equation)
    local temp, s1, s2, op = 0, 0, 0, nil
    for i = 1, #equation do
      local c = equation:sub(i, i)
      if '+' == c or '-' == c or '*' == c or '/' == c then
        op = c
        if temp > 0 then
          s1 = temp
        end
        temp = 0
      elseif '.' == c then
        temp = temp + 1
      end
    end
    s2 = temp
    if '+' == op then
      s2 = s1 + s2
    elseif '-' == op then
      s2 = s1 - s2
    elseif '*' == op then
      s2 = s1 * s2
    elseif '/' == op then
      s2 = s1 // s2
    end
    local s = ""
    for i = 1, s2 do
      s = s .. '.'
    end
    return s  
end
別人簡潔的寫法是:
return function(equation)
    return ('.'):rep(load('return '..equation:gsub('%.+', string.len))())
end
  • 看了別人的code,才知道gsub裡準備取代的字串長度,可以用string.len.
  • string.gsub(s, pattern, repl [, n]) performs global substitutions in string sIt replaces all occurrences of pattern with repl.
    • repl: The replacement value. This can be a string, a table, or a function.
      • If repl is a string, it replaces the matched pattern. Special characters like % have meaning (e.g., %1 refers to the first capture).
      • If repl is a table, the table is indexed with the first capture, and the corresponding value is used as the replacement.
      • If repl is a function, it is called for each match, with the captures as arguments, and its return value is used as the replacement. (string.len是function)
  • 另外:
  • load
    This function compiles a chunk of Lua code from a string and returns it as a function. It does not execute the code immediately.

string.rep is a function in Lua's standard string library that repeats a given string a specified number of times.

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...