I'm completely new to Lua and relatively new to programming, not having done more than BASIC, HyperCard, AppleScript, etc. I'm working my way through the book, but I'm stuck on Exercise 5 in Chapter3, page 114. Here it is:
Code:
-- Returns a function that appends N dots to its argument:
function MakeDotter(N)
Dots = ""
for I = 1, N do
Dots = Dots .. "."
end
return function(Str)
return Str .. Dots
end
end
The question, of course, is What is wrong with this program? The answer the book gives is that Dots is not local. What I don't see is why. True, when you follow the book and do
Code:
OneDotter=MakeDotter(1)
print(OneDotter("A"))
you get
and when you do
Code:
ThreeDotter=MakeDotter(3)
print(ThreeDotter("B"))
you get
and then if you do
Code:
print(OneDotter("C"))
you get
.
But I don't see what that has to do with Dots. Because if you then do
Code:
print(MakeDotter(1)("D"))
you get
just like you should. It seems to me that the problem is with N, not Dots. After all, the value of Dots gets reset to "" --blank--every time the function is called.
Now I'm aware--after trying it with the Lua interpreter at <http://www.lua.org/cgi-bin/demo> (since there is no functional Lua interpeter for Windows Mobile), that making Dots local fixes the problem. What I don't know is WHY.
Help please?