3

My first foray into lua, and this just doesn't work. It says that I'm trying to call global exiter (a nil value). I'm just doing a simple program to try and get functions to work.

print("hello world") io.read() y = 0 while y < 10 do local x = "" print("hello world") x = io.read() if x == "y" then y = exiter(1) print(y) end end function exiter(param) local q = 0 print ("hello again") q = param * 10 return q; end 
1
  • 1
    This is certainly still reproducible and not a simple typo. Commented Aug 8, 2014 at 16:12

3 Answers 3

5

Lua programs are executed top-to-bottom, statement-by-statement. So, when you enter while loop, the function exiter has not come into existence yet. Define it before going into the loop:

function exiter(param) local q = 0 print ("hello again") q = param * 10 return q; end while y < 10 do local x = "" print("hello world") x = io.read() if x == "y" then y = exiter(1) print(y) end end 
Sign up to request clarification or add additional context in comments.

1 Comment

To be clear, functions don't have such identities. exiter is simply a variable that, at some points (end of line 6 to line 16), references a function value created from execution of the function definition (line 1 to line 6).
3

Function definitions occur when the code for them is run. You aren't creating the exiter function until after you try to call it in the while loop. Reverse the order of your loop and function definition.

Comments

3
function exiter(param) -- ... end 

Is simple syntactic sugar for creating a closure and assigning it to exite, which is

  • either a local variable defined earlier in the same or a containing scope,
  • or a global variable (aka element of the environment-table __ENV:
exiter = function(param) -- ... end 

Before you execute the assignment, that variable has its previous value, nil if not yet assigned.

Similar for local function:

local function exiter(param) -- ... end 

is equivalent to first defining a local variable and then doing the same as without local:

local exiter exiter = function(param) -- ... end 

That means any use of exiter before that function statement would not refer to the new local. Defining the local before the assignment is neccessary in order to allow recursive calls, this is not equivalent and does not work:

local exiter = function(param) -- ... cannot recursively call exiter here end 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.