What happened to my luya?

My first foray into lua and it just doesn't work. It says that I am trying to call a global exiter (nil value). I'm just making a simple program to try and get the 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

      

+3


source to share


3 answers


Lua programs are executed from top to bottom, on each statement. So when you enter the loop while

, the function exiter

hasn't appeared yet. Define it before entering 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

      

+5


source


Function definitions arise when you execute code for them. You are not creating the exiter

before after function that you are trying to call in the while loop. Reverse the definition of loop and function.



+3


source


function exiter(param)
    -- ...
end

      

Simple syntactic sugar for creating a closure and assigning it exite

, which is

  • either a local variable previously defined in the same or containing scope,
  • or a global variable (aka element of table-environment __ENV

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

      

Before the job is executed, this variable has its previous value nil

, if it has not already been assigned.

Likewise 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

      

This means that any use exiter

before this function statement will not reference the new local. Defining local before assignment is necessary in order to allow recursive calls, it is not equivalent and does not work:

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

      

+3


source







All Articles