2025年10月6日 星期一

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