I think that there's no such thing as "global" keyword (like in PHP for example) or references in Lua.
There's closures, which will let you access variables defined as local
in a subfunction.
For example:
function makeCounter()
local i = 0
local function counterfunc()
i = i + 1
return i
end
return coutnerfunc
end
local counter1 = makeCounter()
print(counter1()) -- 1
print(counter1()) -- 2
print(counter1()) -- 3
local counter2 = makeCounter()
print(counter2()) -- 1
print(counter2()) -- 2
print(counter1()) -- 4
This means you can store objects for use in your callback function.
function ENT:GetPage()
-- The implicitly-defined self variable...
http.Fetch("www.example.com", function(body)
-- ...is still available here.
self.results = body
end)
end
Note that http.Fetch
is an asynchronous function; it calls the callback later when the page is actually fetched. This won't work:
function ENT:GetPage()
local results
http.Fetch("www.example.com", function(body)
results = body
end)
return results -- The closure hasn't been called yet, so this is still nil.
end