Skip to content

Instantly share code, notes, and snippets.

@eevee
Created August 29, 2016 17:33
Show Gist options
  • Save eevee/e15d43b253265d0189bd7ffe5ecac212 to your computer and use it in GitHub Desktop.
Save eevee/e15d43b253265d0189bd7ffe5ecac212 to your computer and use it in GitHub Desktop.
Lua scope is weird man
-- This works: "bar()" references a global by default, and the next block sets
-- a global variable.
function foo()
bar()
end
function bar()
print("bar")
end
-- This DOESN'T work: "bar()" references a global because Lua hasn't seen
-- anything to the contrary /yet/, and then the next block creates a local, so
-- the global "bar" is never defined, and you get an error about trying to call
-- a nil value.
local function foo()
bar()
end
local function bar()
print("bar")
end
]]
-- This ALSO DOESN'T work: "bar()" references a local, because it appears after
-- "local bar", but "local function bar()" creates a NEW local whose scope
-- begins at that point, so the earlier "bar" is a different variable that's
-- never assigned.
local bar
local function foo()
bar()
end
local function bar()
print("bar")
end
-- This DOES work: "bar()" references a local, and later on that local is
-- assigned normally. Unfortunately, it's very misleading if the "local"
-- statement appears some ways before the actual definition of "bar", which
-- would then look like a global.
-- On the other hand, luacheck complains if you create any globals at all, so
-- if you're using it, you can safely assume nothing is global? I guess?
local bar
local function foo()
bar()
end
function bar()
print("bar")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment