2025年10月6日 星期一

Lua預設的 table.insert 是屬於全域的 table 模組,不是附在每個表(table)上的方法

 7 kyu: Sliding windows

題目很難懂是在做什麼?
尤期是length等於0到底是什麼?
因此嘗試了有點多次,
最後是length = 0的情況,
當做是list table多了一個0的值在一開始,
來解決。
另外就是有關Lua的table,
用insert加入元素,如下code:

> a = {}

> a:insert(123)

stdin:1: attempt to call a nil value (method 'insert')

stack traceback:

stdin:1: in main chunk

[C]: in ?

> table.insert(a, 123)

不能用a:insert(123),
查ChatGPT是說:

預設的 table.insert 是屬於全域的 table 模組,不是附在每個表(table)上的方法。

也就是說,除非你自己把 insert 方法掛到 a 表上,否則 a:insert(123) 會報錯。

要用table.insert(a, 123)
或者

✅ 正確寫法示範:

a = {} a.insert = table.insert -- 將全域的 table.insert 方法掛到 a 上 a:insert("k")

執行後:

print(a[1]) --> k

我Pass的code如下:
local function window(length, offset, list)
  local a, temp, l = {}, {}, {}
  if 0 == length then
    for ii = 0, #list do
      if 0 == ii then
        l[1] = 0
      else
        l[ii + 1] = list[ii]
      end
    end
  else
    l = list
  end
  for i = 1, #l, offset do
      if i + length - 1 <= #l then
        for j = i, i + length - 1 do
          table.insert(temp, l[j])
        end
        table.insert(a, temp)
        temp = {}
      end
  end
  return a
end

return window

Lua table中,key宣告時自帶string

 7 kyu Turn with a Compass

這題不算難,但是我用Lua在table宣告初使值,犯了錯誤,
如下:

> a = {'t' = 1}

stdin:1: '}' expected near '='

這邊't' = 1錯誤,
t應該不用宣告為string, 而是table中的key會自帶string,
宣正如下:

> a = {t = 1}

這樣就正確了。

另外這題我寫的程式碼不是很精簡,
但還是寫出來了,如下:
local function direction(facing, turn)
  local d = {N = 0, 
             NE = 45,
             E = 90,
             SE= 135,
             S = 180,
             SW= 225,
             W = 270,
             NW= 315}
  local t = (d[facing] + turn) % 360
  if 0 == t then
    return 'N'
  elseif 45 == t then
    return 'NE'
  elseif 90 == t then
    return 'E'
  elseif 135 == t then
    return 'SE'
  elseif 180 == t then
    return 'S'
  elseif 225 == t then
    return 'SW'
  elseif 270 == t then 
    return 'W'
  elseif 315 == t then
    return 'NW'
  end
end

return direction

Lua預設的 table.insert 是屬於全域的 table 模組,不是附在每個表(table)上的方法

 7 kyu: Sliding windows 題目很難懂是在做什麼? 尤期是length等於0到底是什麼? 因此嘗試了有點多次, 最後是length = 0的情況, 當做是list table多了一個0的值在一開始, 來解決。 另外就是有關Lua的table, 用insert加...