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
source to share
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
source to share
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
source to share