2025年11月11日 星期二

Lua的table,不能直接比較

 今天在寫

7 kyu: [BUG] XCOM-388: Mass spectrometer crashes

這一題時,
發現empty table的變數跟empty table的值用不相等比較時,
預期會是false (不相等),但其實會傳回true,
如下:

> a = {}

> if a ~= {} then

>>  print(a)

>> end

table: 0x600002bbc640

(後記,非空table比對,也是一樣)
如果要檢查,table是否空時,
可用next檢查,next()為true時,不為空table.
寫出程設題,如下:
local spectrometer = {}

function spectrometer.get_heaviest(atomic_masses)
  if atomic_masses and next(atomic_masses)then
    if #atomic_masses < 500000 then
      return math.max(table.unpack(atomic_masses))
    else
      local m = 0
      for i = 1, #atomic_masses do
        if atomic_masses[i] > m then
          m = atomic_masses[i]
        end
      end
      return m
    end
  else
    return 0
  end
end

return spectrometer
別人寫的跟我的大致類似,
除非用第三方的API,才有比較簡潔的寫法。

用Lua算UTF-8字串的長度

 7 kyu: Count of codepoints in a UTF-8 string

題目是算UTF-8字串的長度,

這題我實在不知道啥好方法,

可能也不太了解題目,

但是想到這種格式轉換,

在實際應用上,都是直接查答案的,

因此就直接問AI了,

AI的解法如下:

local function count_codepoints(s)
    local count = 0
    for i = 1, #s do
        local b = s:byte(i)
        -- b < 128: ASCII
        -- b >= 192: UTF-8 leading byte
        if b < 128 or b >= 192 then
            count = count + 1
        end
    end
    return count
end

return count_codepoints

不過這題AI最先的解法,

其實很多餘,

Lua 5.3+Lua 5.4 裡,其實已經內建,

採用以下的解法就好:

return utf8.len


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

Lua的table,不能直接比較

 今天在寫 7 kyu: [BUG] XCOM-388: Mass spectrometer crashes 這一題時, 發現empty table的變數跟empty table的值用不相等比較時, 預期會是false (不相等),但其實會傳回true, 如下: > a =...