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基本運算的簡潔寫法

 7 kyu: Dot Calculator 這題是用"."點的數目表示數字,並給operator做運算。 我的寫法是: return function ( equation ) local temp , s1 , s2 , op = 0 , 0...