Programming In Lua Exercises

lua-users home
wiki

These are community contributed solutions to some of the PiL3 exercises.

Chapter 3

Exercise 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

Exercise 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

Chapter 8

Exercise 8.4

Can you find any value for f such that the call pcall(pcall,f) returns false as its first result?

Using the debug library ([source]):

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)

Another idea is to have the extra "true" added by the inner pcall overflow the call stack ([source]).


RecentChanges · preferences
edit · history
Last edited March 6, 2013 8:00 pm GMT (diff)