Lua 程式練習題

lua-users home
wiki

以下是社區貢獻的 PiL3 練習題解決方案。

第 3 章

練習題 3.4

-- Recursive solution; the basic idea is to keep factoring out x until
-- we reach a 0 level polynomial:
--
--   3x^3 + 2x^2 + x + 3
-- = (3x^2 + 2x + 1) * x + 3
-- = (((3x + 2) * x) + 1) * x + 3
-- = ((((3 * x) + 2) * x) + 1) * x + 3
--
-- N.b. this algorithm requires that there be no gaps in the series of
-- coefficients. If there is no exponent for a particular power then the
-- coefficients list must contain a 0.

function poly (coefficients, x)
    size = #coefficients
    if size < 0 then
	print ("Error: algorithm requires positive coefficients")
    elseif size == 0 then 
        return 0
    else
	c = coefficients[size]
	coefficients[size] = nil
        return c + x * poly(coefficients, x) 
    end
end

print (poly({4,3,0,1}, 10))	-- gives 4301

練習題 3.5

-- The key is on p.22: lua returns false for comparisons between different
-- types, so only a boolean (or a nil) will return true when compared to true
-- or to false. 

function test (candidate)
    print (candidate == true or candidate == false)
end

candidates = {5, 0, "hello", {2,3,4}, true, false}

-- gives false, false, false, false, true, true
for k, v in pairs(candidates) do
    print (test(v))
end

第 8 章

練習題 8.4

你能找到 f 的任何值,使得呼叫 pcall(pcall,f) 會傳回 false 作為第一個結果嗎?

使用 debug 函式庫 ([來源])

local f = function()
  local h = function()
    if c then debug.sethook(nil,"r") end
    c = not c
    error()
  end
  debug.sethook(h,"r")
end
pcall(pcall,f)

另一個想法是讓額外的「true」由內部的 pcall 加入,溢位呼叫堆疊 ([來源]).


近期變更 · 喜好設定
編輯 · 歷程記錄
最後編輯於 2013 年 3 月 6 日晚上 8:00(格林威治標準時間)(差異)