Access variables in different files

General discussion about LÖVE, Lua, game development, puns, and unicorns.
Post Reply
soulgirl2020
Prole
Posts: 6
Joined: Thu Jun 18, 2020 11:47 pm

Access variables in different files

Post by soulgirl2020 »

I am trying to create a basic zelda game and so far I have the main, player, util, animation, enemy1, and a struggling physics engine. I'm trying to use a global variable from main (tileWidth) and use it in player. It says that it is nill, and I've tried putting it in love.load and above it at the top but it still returns nill. I have all the files required in main as well. Also, how would I go about using player.x, player.y, etc in another file? My biggest issue is connecting the files.
Attachments
Player.lua
(11.95 KiB) Downloaded 222 times
User avatar
4vZEROv
Party member
Posts: 126
Joined: Wed Jan 02, 2019 8:44 pm

Re: Access variables in different files

Post by 4vZEROv »

When you write require('file') you are essentially pasting all the content of the file at the place of the require line.
Also you can see here : https://love2d.org/wiki/love.run where the love.load() function is really called inside the love2d game loop.

If you want to use a global variable in the file 'fileexemple.lua'

--main.lua

Code: Select all

my_global_variable = 100
require('fileexemple')
--fileexemple.lua

Code: Select all

print(my_global_variable )
Your player file look like a class.
If you want to use it, you need to instantiate it.

Code: Select all

	global_var = 100
	require('player')
	local my_player = player:init()
soulgirl2020
Prole
Posts: 6
Joined: Thu Jun 18, 2020 11:47 pm

Re: Access variables in different files

Post by soulgirl2020 »

OMG! Thank you so much, it works now. I did not instantiate the class file in main.lua. :)
Post Reply

Who is online

Users browsing this forum: No registered users and 0 guests