BlaztOne
BlaztOne

Reputation: 180

This local function can be accessed outside the scope, any explanation?

for i = 1, 20 do  --Create a loop
  if i < 10 then 
    local function LessThan10() 
      return i
    end 
  end
end 
print(LessThan10())

Surprisingly, eventhough LessThan10 was inside a conditional statement and it was a local function(actually it's not the function, it's the variable). Somehow, I could still print out the answer

This is pretty interesting (I checked in Zerobrane, LessThan10 is a local function)

EDIT : Well I guess it's my interpreter problem, I changed the interpreter and this thing errors.

Upvotes: 0

Views: 113

Answers (2)

Coal
Coal

Reputation: 344

Tested in Lua 5.0 interpreter:

Lua 5.0.3  Copyright (C) 1994-2006 Tecgraf, PUC-Rio
> for i = 1, 20 do  --Create a loop
>>   if i < 10 then
>>     local function LessThan10()
>>       return i
>>     end
>>   end
>> end
> print(LessThan10())
stdin:1: attempt to call global `LessThan10' (a nil value)
stack traceback:
        stdin:1: in main chunk
        [C]: ?

I also can't believe this is / was valid code as local variables are only visible within the block they are declared at.

If you are using a custom Lua interpreter you should further investigate on it, seems pretty interesting though.

Upvotes: 1

BlaztOne
BlaztOne

Reputation: 180

I tested this and it only worked on Lua 5.0 and 5.1

I tested it again on Lua 5.3 and it no longer works

My zerobrane reset my lua version to 5.0 for no reason, well, sorry if this question disappointed you.

Upvotes: 0

Related Questions