MrPRambo
MrPRambo

Reputation: 125

What's wrong with my lua?

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

Upvotes: 3

Views: 153

Answers (3)

Deduplicator
Deduplicator

Reputation: 45704

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

Upvotes: 3

hjpotter92
hjpotter92

Reputation: 80653

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

Upvotes: 5

Etan Reisner
Etan Reisner

Reputation: 81052

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.

Upvotes: 3

Related Questions