Code: Select all
local a = function(i)
i=i+1
if i == 5 then
return i
else
return a(i)
end
end
print(a(1))
Code: Select all
input:6: attempt to call a nil value (global 'a')
Code: Select all
local a = function(i)
i=i+1
if i == 5 then
return i
else
return a(i)
end
end
print(a(1))
Code: Select all
input:6: attempt to call a nil value (global 'a')
Finally, a subtle point regarding recursive private methods. If you need to create a private method that calls himself, you will need to declare the variable first, and then (on the next line) initialize it with the function value. Otherwise the variable will not be available when the function is created
Code: Select all
MyClass3 = class('MyClass3')
local _secretRecursiveMethod -- variable declared here
_secretRecursiveMethod= function(self, n) -- and initialized here
if(n<=0) then
print( 'Last recursion')
else
print ( 'Recursion level ' .. n )
_secretRecursiveMethod(self, n-1)
end
end
MyClass3:recurseOver(n)
_secretRecursiveMethod(self, n)
end
Code: Select all
local a
a = function(i)
i=i+1
if i == 5 then
return i
else
return a(i)
end
end
print(a(1))
Code: Select all
local function a(i)
-- code
end
Code: Select all
local a = function(i)
local a = {debug.getlocal(2,1)}
a = a[2]
i = i+1
if i == 5 then
return i
end
return a(i)
end
print(a(1))
Code: Select all
-- The syntax sugar
local function name(arg)
-- something
end
-- is actually equivalent to:
local name; name = function(arg)
-- something
end
-- and NOT to:
local name = function(arg)
-- something
end
-- for the exact reason that the last one can not call itself.
Code: Select all
-- Just to illustrate what i mean:
-- this works:
local t = {a = 1, b = 2}
t.b = t.a
-- these do not:
local t = {a = 1, b = a} -- b is set to nil.
local t = {a = 1, b = t[a]} -- errors because i basically did nil[something], where something in this case was nil as well.
Users browsing this forum: Google [Bot] and 180 guests