Page 1 of 1

question about local and global [SOLVED]

Posted: Mon Apr 29, 2019 4:26 am
by test
Whats the difference between the codes above?

Code: Select all

function love.load()
x = 10
end

Code: Select all

local x
function love.load()
x = 10
end
In the second code, x is local. But in the first code, is it global or local? I think both codes is the same.

Re: question about local and global

Posted: Mon Apr 29, 2019 5:25 am
by raidho36
The difference is technical: global variables are stored in a globally accessible table (it's called _G and you can access it manually), and local variables are stored in Lua VM registers. For that reason, globals are accessible everywhere, but locals only accessible within the scope they were defined (file, function, block of code, etc). For the same reason, locals are faster, and are limited to 200 at a time in any given scope.

Re: question about local and global

Posted: Mon Apr 29, 2019 5:34 am
by ivan
Put simply: in the second example the 'x' variable cannot be accessed outside of the file because it's local.

Re: question about local and global

Posted: Mon Apr 29, 2019 6:25 am
by test
So x in the first code is global right?

Re: question about local and global

Posted: Mon Apr 29, 2019 6:32 am
by arampl
Yes. Variables in Lua are global by default.

Re: question about local and global

Posted: Mon Apr 29, 2019 6:54 am
by zorg
Global to the lua state, anyway (with löve, it may matter, since you can have multiple synchronous threads that have their own lua states), but the globals are really just keys in a table that's, by default, as raidho already said.

Re: question about local and global

Posted: Mon Apr 29, 2019 1:13 pm
by pgimeno
Here's how you can tell the difference between a global and a local.

main.lua:

Code: Select all

function love.load()
  x = 10
  require 'extra'
end
extra.lua:

Code: Select all

print(x)
That will print 10, because x is a global, therefore it's accessible from every file in the current thread.

Now if you add this at the top of main.lua:

Code: Select all

local x
it will print 'nil' because the second file is accessing the global variable x, which does not exist, because x is local to main.lua, and there isn't a global with that name.