Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with my lua?

Tags:

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
like image 478
MrPRambo Avatar asked Mar 04 '26 17:03

MrPRambo


2 Answers

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
like image 154
hjpotter92 Avatar answered Mar 06 '26 08:03

hjpotter92


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.

like image 21
Etan Reisner Avatar answered Mar 06 '26 07:03

Etan Reisner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!