Programming In 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)

另一个想法是让内部 pcall 添加的额外的 "true" 溢出调用堆栈 ([来源]).


最近更改 · 偏好设置
编辑 · 历史记录
最后编辑于 2013 年 3 月 6 日下午 8:00 GMT (差异)