Page 1 of 1

Problems with localising variables

Posted: Tue Jan 21, 2020 8:48 pm
by bobbymcbobface
hay all,

i need some help with a variable I'm trying to use from one file to another

i don't know exactly what I've done but i know my variable can't be called from the second file even know I'm using the return function
can someone please have look at my code and see what I've done wrong because I'm stumped on this one

~Thank you!
Snake.love
(4.59 MiB) Downloaded 232 times

Re: Problems with localising variables

Posted: Tue Jan 21, 2020 9:25 pm
by MrFariator
As far as I can tell, you are doing something along the lines of...

Code: Select all

-- bottom of Game.lua
return Game, Menu.Snake

-- in main.lua
local Game = require("Game") -- 'Menu.Snake' from Game.lua is not assigned to anything
And this is repeated across most of the files. If you have multiple return values, you need to assign each of those separately. Otherwise it will pick the first value returned, and ignore the rest.

Code: Select all

-- example
function sample()
  return 0, 1, 2, 3
end

local a,b,c,d,e = sample()
print(a) -- 0
print(b) -- 1
print(e) -- nil, because only a,b,c,d received values
Reading your code, I don't know which variable you are having trouble with specifically, or where for that matter (I couldn't get the .love to crash when I ran it), so you'll have to elaborate if you need further help.

Re: Problems with localising variables

Posted: Wed Jan 22, 2020 12:05 am
by zorg
One more complication, require can only return 1 result.

Re: Problems with localising variables

Posted: Wed Jan 22, 2020 4:20 pm
by KayleMaster
zorg wrote: Wed Jan 22, 2020 12:05 am One more complication, require can only return 1 result.
That's why you return a table with your results:

Code: Select all

-- bottom of Game.lua
return {Game, Menu.Snake}

-- in main.lua
local Game = require("Game")[1]
local Menu.Snake= require("Game")[2]
Don't worry about require being called twice - its result is 'cached' after the first call.
EDIT: I guess you could also use unpack()

Re: Problems with localising variables

Posted: Wed Jan 22, 2020 4:39 pm
by raidho36
If your module needs to return multiple values, consider that it might actually be two modules crammed into one, and you just need to split them.

Re: Problems with localising variables

Posted: Thu Jan 23, 2020 7:56 pm
by bobbymcbobface
tnx guys! i'll get back to you if any have any problems if not, again, thanks :D